Chapter 15: Unit testing in Spring apps
The chapter introduction defines tests, distinguishes unit from integration tests, and explains why testing protects an app’s capabilities over time.
After this chapter you will be able to
- Test Purpose and Categories. Explain what a test validates and distinguish unit tests from integration tests by what each focuses on.
- Long Term Value of Tests. Explain how tests help during development and why their value may be greater than their immediate visible impact.
- Regression testing value. Explain why tests are worth writing even when a capability initially works. Describe how rerunning them after code changes can reveal broken existing behavior before production.
- Scenario based test organization. Describe how to organize tests for a method: identify its relevant behavior scenarios and write a separate test method for each in a test class focused on that method.
- Requirement driven expected behavior. Explain how a test scenario must check the behavior the app’s requirements call for, using an insufficient-funds money transfer as an example.
- Unit Test Isolation. Explain why a unit test focuses on one flow of a small piece of logic under defined conditions, without relying on its real dependencies. Distinguish the confidence it provides from testing whether Spring-provided dependencies are wired correctly.
- Three Part Test Structure. Describe how to write a test by defining inputs and dependency behavior, calling the tested method, and validating what happens. Apply that structure to a happy flow, in which the use case completes without errors or exceptions.
- Controlled Repository Mock. Explain why the money-transfer unit test substitutes a mock for AccountRepository, how it specifies findById() behavior, and how it checks the service's repository calls.
- Exception Flow Safeguards. Describe how to test a money-transfer exception flow and why checking the thrown exception alone is insufficient.
What it builds on
- Using transactions in Spring apps (chapter 13) · The money-transfer use case used as the section’s testing example.
- Using Spring Data JDBC (chapter 14) · The money-transfer use case provides the service and repository example being tested.
Section by section
Introduction
The chapter introduction defines tests, distinguishes unit from integration tests, and explains why testing protects an app’s capabilities over time.
- Test Purpose and Categories: Explain what a test validates and distinguish unit tests from integration tests by what each focuses on.
Why it matters: This distinction helps you tell what a test is checking before you discuss how to write it. - Long Term Value of Tests: Explain how tests help during development and why their value may be greater than their immediate visible impact.
Why it matters: Testing helps preserve the behavior users depend on as an app changes.
Key terms: test, unit tests, integration tests, tests, existing capabilities, documentation, business value
15.1 Writing correctly implemented tests
This section explains why automated tests matter and how to organize tests around the different ways a method should behave.
- Regression testing value: Explain why tests are worth writing even when a capability initially works. Describe how rerunning them after code changes can reveal broken existing behavior before production.
Why it matters: A passing manual check today does not show that the capability will survive tomorrow’s code changes. - Tests in continuous integration: Describe how continuous integration makes test execution part of the build after developers make changes and reports failures to them.
Why it matters: Putting tests in the build helps teams get feedback without depending on someone remembering to run them. - Scenario based test organization: Describe how to organize tests for a method: identify its relevant behavior scenarios and write a separate test method for each in a test class focused on that method.
Why it matters: Separating scenarios makes it clear which behavior each test checks. - Requirement driven expected behavior: Explain how a test scenario must check the behavior the app’s requirements call for, using an insufficient-funds money transfer as an example.
Why it matters: A test is useful only if its expected result matches the behavior the app is supposed to provide. - Small methods and testability: Explain why separating responsibilities into small, readable methods makes relevant test scenarios easier to identify and supports maintainability.
Why it matters: Method design affects how readily you can work out what needs testing.
Key terms: regression testing, tests, continuous integration (CI), build process, CI tool, test scenario, test method, test class, app’s requirements, credit limit
15.2 Implementing unit tests in Spring apps
This section shows how to unit-test Spring application logic in isolation by controlling dependencies and checking successful, exceptional, and returned-value outcomes.
- Unit Test Isolation: Explain why a unit test focuses on one flow of a small piece of logic under defined conditions, without relying on its real dependencies. Distinguish the confidence it provides from testing whether Spring-provided dependencies are wired correctly.
Why it matters: Isolation makes failures easier to locate while clarifying what a unit test cannot prove. - Three Part Test Structure: Describe how to write a test by defining inputs and dependency behavior, calling the tested method, and validating what happens. Apply that structure to a happy flow, in which the use case completes without errors or exceptions.
Why it matters: The setup, call, and validation sequence gives each test a clear scenario and expected result. - Controlled Repository Mock: Explain why the money-transfer unit test substitutes a mock for AccountRepository, how it specifies findById() behavior, and how it checks the service's repository calls.
Why it matters: Controlling and checking the repository mock keeps the transfer test about service logic rather than repository implementation. - Annotated Mock Setup: Describe the annotation-based alternative to creating the repository mock and tested service manually, including the extension needed to enable the annotations.
Why it matters: This is an alternative way to prepare the same isolated test objects. - Exception Flow Safeguards: Describe how to test a money-transfer exception flow and why checking the thrown exception alone is insufficient.
Why it matters: An error response is not enough if the method has already made an invalid change. - Login Outcome Assertions: Describe how the login-controller unit test controls its collaborators and checks both the returned view name and the message added to the Model.
Why it matters: A controller test may need to check both what its method returns and what it does to a collaborator.
Key terms: unit test, isolated, dependencies, Spring-based tests, assumptions, call/execution, validations, happy flow, arrange, act, and assert, AccountRepository
15.3 Questions
This section offers self-check questions about testing concepts, with answers in Appendix A.
15.4 Summary
Summarizes why tests matter, how unit and integration tests differ, why mocks are used, and the three parts of a test.
Where this is used later
- Implementing Spring integration tests (chapter 16) · The definition of integration tests frames tests of interacting components.
- (chapter intro) (chapter 16) · Prior work on implementing unit tests.
- Implementing controller integration tests (chapter 16) · unit testing application logic
Concepts explained in this chapter
- unit testA unit test checks the behavior of a small, isolated unit of code.
- mockingA mock object is a controllable test double that simulates a dependency and allows its interactions to be inspected or verified.
- regression testRegression testing is repeated testing of existing functionality to verify that code changes have not broken it.
- test classA test class is a class that groups automated test methods for related application behavior.
- test scenarioA test scenario is a distinct combination of conditions and inputs representing a way an application may behave that should be validated.
- testabilityTestability is the degree to which software can be tested effectively and efficiently.
- integration testAn integration test verifies behavior across multiple integrated components or systems.
- software testingThe systematic evaluation of software behavior against expected requirements or outcomes.
- @InjectMocks annotationThe Mockito @InjectMocks annotation marks an object for creation with mock dependencies injected into its constructor, fields, or methods.
- @Mock annotationThe Mockito @Mock annotation marks a field or parameter for automatic initialization as a mock object.
- ExtendWithThe JUnit Jupiter @ExtendWith annotation registers one or more extensions that integrate with the test lifecycle.
- MockitoMockito is a Java mocking framework for creating configurable test doubles and verifying their interactions.
- MockitoExtensionMockitoExtension is a JUnit Jupiter extension that initializes Mockito annotations and integrates Mockito with test execution.
- assertThrowsThe JUnit assertion method assertThrows() executes code and verifies that it throws an expected exception type.
- beforeEachThe @BeforeEach annotation marks a JUnit Jupiter method for execution before each test method.
- given() methodThe Mockito given() method defines the behavior a mock exhibits when a specified method call occurs.
- mock methodThe Mockito mock() method creates a mock object for a specified Java type.
- never() verification modeThe Mockito never() method returns a verification mode that checks that a mock method was not called.
- verify() methodThe Mockito verify() method checks whether a specified interaction with a mock occurred.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
