Basics Flashcards
Arrange, Act and Assert
A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior. If the observed behavior is consistent with the expectations, the unit test passes, otherwise, it fails, indicating that there is a problem somewhere in the system under test.
Types of unit tests
Verifying that the system under test produces correct results, or that its resulting state is correct, is called state-based unit testing, while verifying that it properly invokes certain methods is called interaction-based unit testing.
True Unit Tests
Unit tests should fail only if there’s a bug in the system under test.
For example, tests may pass when running one-by-one, but fail when running the whole test suite, or pass on our development machine and fail on the continuous integration server. These situations are indicative of a design flaw. Good unit tests should be reproducible and independent from external factors such as the environment or running order.
@Test
@Test
void testGetAge() {
Person person = new Person(“Joey”, “Doe”, LocalDate.parse(“2013-01-12”));
long age = person.getAge();
assertEquals(4, age);
}
JUnit 5
Junit 5 is the latest version of the testing framework, and it has a lot of features when compared with Junit 4. JUnit 5, also known as JUnit Jupiter
@BeforeEach
Indicates that the annotated method should be executed before each test.
@AfterEach
Indicates that the annotated method should be executed after each test.
@BeforeAll
Indicates that the annotated method should be executed before all tests in the test class.
@AfterAll
Indicates that the annotated method should be executed after all tests in the test class.
@DisplayName
Provides a custom name for the test class or test method.
@Disabled
Disables the test method or class.
Parameterized Tests
This Parameterized Test is used to test a Test case with different parameters for this we use @ParameterizedTest annotations.
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
void testSquare(int value) {
int result = square(value);
assertEquals(value * value, result, “Square calculation is incorrect”);
}
Test Lifecycle
https://media.geeksforgeeks.org/wp-content/uploads/20231228120919/JUnit-5-test-Lifecycle-660.png
Lifecycle Methods
A method annotated or meta-annotated with @BeforeAll, @AfterAll, @BeforeEach, or @AfterEach.
Test Class
A top-level class that contains at least one test method. It must not be abstract class.