Contents
JUnit & Mockito
Testing Java code: JUnit tests, assertions, parameterized tests and Mockito mocks.
1.Getting started
- Why tests and what JUnit isWhat automated tests give you, how JUnit, Mockito and AssertJ split the work, which versions the course uses and what we are going to test.
- Project setupA Maven project for tests: the JUnit BOM, the junit-jupiter dependency, the Surefire plugin, the src/test/java folder and the first class under test.
- The first testA test class, the @Test annotation, assertEquals and the arrange, act, assert structure on the price calculator example.
- Running tests and reading the resultsmvn test, running one class or one method, how to read the Surefire report, the difference between a failure and an error, and which classes are considered tests.
2.JUnit basics
- AssertionsThe main JUnit assertions: assertEquals, assertTrue, assertNull, assertIterableEquals, messages for failures and grouping checks with assertAll.
- Exceptions and timeoutsHow to check that code throws the right exception with assertThrows, inspect its message, check the absence of an exception and limit the run time with assertTimeout.
- Test lifecycleThe blog service under test, preparing fresh objects with @BeforeEach, cleaning up with @AfterEach, one-time setup with @BeforeAll and @AfterAll, and why each test gets a new instance of the class.
- Readable names and nested classes@DisplayName for human-readable test names and @Nested for grouping tests of one class by situation, with shared and nested setup.
- Disabling, assumptions and tagsTemporarily disabling a test with @Disabled, skipping it under conditions with assumptions and @EnabledOnOs, marking tests with @Tag and running only some groups through Maven.
3.More JUnit features
- Parameterized testsOne test for many inputs: @ParameterizedTest with @ValueSource, @NullAndEmptySource and @CsvSource, readable names of runs and quoting in CSV.
- Data from a method: @MethodSourceWhen annotations are not enough: supplying objects such as BigDecimal and records to a parameterized test from a factory method with @MethodSource and Arguments.
- Temporary files: @TempDirTesting code that writes files: a temporary folder from JUnit with @TempDir on a field or a parameter, and why tests must not write to fixed paths.
- Fluent assertions with AssertJAdding AssertJ, assertThat chains for strings, numbers, BigDecimal and collections, extracting fields of records, checking exceptions and reading AssertJ failure messages.
- Repeated and dynamic tests, test orderRunning a test several times with @RepeatedTest and RepetitionInfo, building tests at run time with @TestFactory and DynamicTest, and setting the order of tests with @TestMethodOrder and @Order.
- Soft assertions and more AssertJ checksCollecting all failures of a test with AssertJ SoftAssertions and assertSoftly, how they compare to JUnit assertAll, and the checks satisfies, allSatisfy and usingRecursiveComparison.
4.Mockito
- Mocks: mock, when, thenReturnWhy a unit test replaces dependencies, adding Mockito with the Java agent setup for modern JDKs, creating a mock and stubbing methods with when and thenReturn.
- Checking calls: verifyHow to check with verify that the service called a dependency with the right arguments, the right number of times or not at all, and how to read Mockito's messages.
- Argument matchers and ArgumentCaptorStubbing and verifying calls with any argument using any, anyLong, eq and contains, computing the result with thenAnswer and catching the argument with ArgumentCaptor.
- Errors from dependencies: thenThrow and doThrowSimulating a failing database or mail server with thenThrow, doThrow for void methods, different answers for consecutive calls and the rule about checked exceptions.
- @Mock and @InjectMocks with MockitoExtensionCreating mocks with annotations: @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks and @Captor, plus strict stubbing and the UnnecessaryStubbingException.
- SpiesWhat a spy is in Mockito, how it differs from a mock, verifying calls on a real object and replacing one method with doReturn.
- Call order, static methods and constructorsChecking the order of calls with InOrder, replacing static methods such as LocalDate.now with mockStatic, intercepting new with mockConstruction, and why injecting a Clock is better.
- BDD style: given, willReturn, then, shouldWriting Mockito tests in the given-when-then style with BDDMockito, naming tests by situation and result, and creating spies with the @Spy annotation.
5.Good tests
- What makes a good testProperties of good unit tests, what to test and what not to, how many mocks are too many, naming, and why tests must not share state.
- Test coverage with JaCoCoWhat code coverage measures, adding the JaCoCo plugin to Maven together with the Mockito agent, reading the HTML report and why 100% is not the goal.