|
| 1 | +package com.baeldung.initializationguide; |
| 2 | +import org.junit.Before; |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import static org.assertj.core.api.Assertions.*; |
| 6 | + |
| 7 | +import java.io.BufferedInputStream; |
| 8 | +import java.io.BufferedOutputStream; |
| 9 | +import java.io.FileInputStream; |
| 10 | +import java.io.FileNotFoundException; |
| 11 | +import java.io.FileOutputStream; |
| 12 | +import java.io.IOException; |
| 13 | +import java.io.ObjectInputStream; |
| 14 | +import java.io.ObjectOutputStream; |
| 15 | +import java.lang.reflect.InvocationTargetException; |
| 16 | +import java.nio.file.Files; |
| 17 | +import java.nio.file.Path; |
| 18 | +import java.nio.file.Paths; |
| 19 | + |
| 20 | +public class UserTest { |
| 21 | + |
| 22 | + |
| 23 | + Path userData; |
| 24 | + |
| 25 | + @Before |
| 26 | + public void init() throws IOException { |
| 27 | + userData = Paths.get("src/test/resources/user.data"); |
| 28 | + if (!Files.exists(userData)) |
| 29 | + Files.createFile(userData); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() { |
| 34 | + User user = new User("Alice", 1); |
| 35 | + assertThat(user).isNotNull(); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { |
| 40 | + User user = User.class.getConstructor(String.class, int.class) |
| 41 | + .newInstance("Alice", 2); |
| 42 | + assertThat(user).isNotNull(); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException { |
| 47 | + User user = new User("Alice", 3); |
| 48 | + User clonedUser = (User) user.clone(); |
| 49 | + assertThat(clonedUser).isEqualTo(user); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void givenFileWithBitsRepresentingUser_whenDeserialized_thenUserIsCreated() throws FileNotFoundException, IOException, ClassNotFoundException { |
| 54 | + try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(userData.toFile())))) { |
| 55 | + User user = new User("Tom", 0); |
| 56 | + out.writeObject(user); |
| 57 | + } |
| 58 | + try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(userData.toFile())))) { |
| 59 | + User deserializedUser = (User) in.readObject(); |
| 60 | + assertThat(deserializedUser).isNotNull(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + @Test |
| 65 | + public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() { |
| 66 | + User user = new User(); |
| 67 | + assertThat(user.getName()).isNull(); |
| 68 | + assertThat(user.getId() == 0); |
| 69 | + } |
| 70 | +} |
0 commit comments