Practice: testing Spring applications
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Testing a Spring app well takes two skills: picking the cheapest test that can prove a check, and reading a failing test's message fast enough to fix it. This optional page drills both on ShopLite's code.
Picking the right test for a check
Ask what the check needs, then pick the cheapest test that can prove it. The program below applies the rules to six ShopLite checks.
Example 1 · Choosing the cheapest test that proves a check
import java.util.List;
/** What a check needs decides the test: the cheapest test that can prove it wins. */record Check(String what, boolean needsHttp, boolean needsSql, boolean needsSecurityRules, boolean needsWholeApp) {}
public class SliceChooserDemo { static String choose(Check check) { if (check.needsWholeApp() || check.needsSecurityRules()) { return "@SpringBootTest"; } if (check.needsHttp() && check.needsSql()) { return "@SpringBootTest"; } if (check.needsHttp()) { return "@WebMvcTest"; } if (check.needsSql()) { return "@DataJpaTest"; } return "plain unit test"; }
public static void main(String[] args) { List<Check> checks = List.of( new Check("duplicate category name throws AlreadyExistsException", false, false, false, false), new Check("blank name gives 400 with an errors list", true, false, false, false), new Check("findByName ignores case on MySQL", false, true, false, false), new Check("a customer gets 403 on POST /api/v1/categories", true, false, true, false), new Check("create a category, then GET it from MySQL", true, true, false, false), new Check("the app starts and every bean is wired", false, false, false, true)); for (Check check : checks) { System.out.printf("%-17s <- %s%n", choose(check), check.what()); } }}plain unit test <- duplicate category name throws AlreadyExistsException @WebMvcTest <- blank name gives 400 with an errors list @DataJpaTest <- findByName ignores case on MySQL @SpringBootTest <- a customer gets 403 on POST /api/v1/categories @SpringBootTest <- create a category, then GET it from MySQL @SpringBootTest <- the app starts and every bean is wired
What this code does
- Each check records what it needs: HTTP, SQL, the security rules or the whole app.
- The order of the
ifs is the advice: whole app or security first, then the cheaper slices, then a plain unit test. - "Create a category, then GET it from MySQL" needs HTTP and SQL together, so it is a
@SpringBootTestflow.
Ask what the check needs:
- A rule inside one class: a plain unit test.
- HTTP shapes (URLs, status codes, JSON, validation):
@WebMvcTest. - Queries and constraints:
@DataJpaTeston MySQL. - Security rules, wiring and flows across layers:
@SpringBootTest.
When two answers fit, pick the cheaper one: it runs faster and fails closer to the bug.
Fix 1: 'No qualifying bean' in a slice
Fix 1: the slice built a controller whose service has no mock. Read the last Caused by: it names the bean (categoryController) and the missing type (CategoryService).
@WebMvcTest(CategoryController.class) // one controller: one service to mock@Import(OpenWebMvcTestSecurity.class)class CategoryControllerTest {
@MockitoBean private CategoryService categoryService; // CategoryController's constructor parameter 0}In @WebMvcTest, add a @MockitoBean for every dependency of every controller in the slice, and name only the controllers under test. A mock for a type no controller uses (a stray ProductService in an order test) does nothing.
Fix the error
Mock the right service
The test mocks a service, but the error names another. Pick the fix.
Which replacement for line 3 fixes the error?
Error
No qualifying bean of type 'com.shoplite.product.ProductService' available
Fix 2: wrong profile, wrong database
Run a repository test without the test profile and read the real failure. Example 2 shows the placeholder error.
Example 2 · A repository test without the test profile
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)// forgot: @ActiveProfiles("test")class CategoryRepositoryIT { ...}[ERROR] com.shoplite.category.CategoryRepositoryIT.findByNameIgnoresCase -- Time elapsed: 0.004 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@2f4d32a9 testClass = com.shoplite.category.CategoryRepositoryIT, ...]
...
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'DB_PASSWORD' in value "${DB_PASSWORD}"
(With DB_PASSWORD set in your shell, the same test would instead start on the dev database `shoplite`.)What this code does
- The dev profile's
${DB_PASSWORD}has no default, so the property cannot be resolved and the context stops. - That failure is the lucky case: with the variable set, the test would run on the dev data.
- Adding
@ActiveProfiles("test")switches toshoplite_testand the test profile's defaults.
Without @ActiveProfiles("test") ShopLite falls back to the dev profile. Its application.properties reads ${DB_PASSWORD} with no default, so the context fails with "Could not resolve placeholder 'DB_PASSWORD'" when the variable is not set. When it is set, the test quietly runs on your dev database, which is worse.
The fix is the annotation, plus the safety layers from the test-data lesson: the profile set in Surefire and Failsafe, and the database guard.
Fix 3: 403 (or 401) instead of 200
Send requests through a web slice that has no open test security and see which refusal you get. Example 3 shows a GET and a POST; Example 4 maps failure messages to the first fix.
Example 3 · A web slice without the open test security
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
@WebMvcTest(CategoryController.class) // forgot: @Import(OpenWebMvcTestSecurity.class)class CategoryControllerTest {
@Autowired private MockMvc mockMvc;
@MockitoBean private CategoryService categoryService;
@Test void getReturnsOneCategory() throws Exception { given(categoryService.get(2)).willReturn(new CategoryResponse(2, "Mobiles", 1)); mockMvc.perform(get("/api/v1/categories/2")).andExpect(status().isOk()); }
@Test void createReturns201() throws Exception { given(categoryService.create(any())).willReturn(new CategoryResponse(8, "Wearables", null)); mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON) .content(""" {"name": "Wearables"} """)) .andExpect(status().isCreated()); }}[ERROR] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 3.402 s <<< FAILURE! -- in com.shoplite.category.CategoryControllerTest [ERROR] com.shoplite.category.CategoryControllerTest.getReturnsOneCategory -- Time elapsed: 0.161 s <<< FAILURE! java.lang.AssertionError: Status expected:<200> but was:<401> [ERROR] com.shoplite.category.CategoryControllerTest.createReturns201 -- Time elapsed: 0.012 s <<< FAILURE! java.lang.AssertionError: Status expected:<201> but was:<403>
What this code does
- Without
OpenWebMvcTestSecurity, the slice uses Boot's default security, not ShopLite'sSecurityConfig. - The GET has no login, so 401; the POST also has no CSRF token, so 403 before any login check helps.
- Adding
@Import(OpenWebMvcTestSecurity.class)fixes both; ShopLite's real rules are tested in the*ITsecurity tests.
Example 4 · From failure message to first fix
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
/** A small "first look" helper: match a failure message to its usual cause and fix. */public class FailureDiagnosisDemo { static final Map<String, String> KNOWN = new LinkedHashMap<>();
static { KNOWN.put("No qualifying bean of type", "the slice lacks a bean -> add @MockitoBean for it, or name only the controller under test"); KNOWN.put("Could not resolve placeholder", "a property has no value -> the test runs with the wrong profile; add @ActiveProfiles(\"test\")"); KNOWN.put("Failed to replace DataSource with an embedded database", "no H2 on the classpath -> @AutoConfigureTestDatabase(replace = Replace.NONE)"); KNOWN.put("Status expected:<200> but was:<403>", "security refused -> missing OpenWebMvcTestSecurity (CSRF), wrong role, or jwt() without authorities"); KNOWN.put("Status expected:<201> but was:<415>", "the body was not read as JSON -> .contentType(MediaType.APPLICATION_JSON)"); KNOWN.put("UnnecessaryStubbingException", "a stub the code never used -> remove it or fix the arguments"); }
static String diagnose(String message) { for (Map.Entry<String, String> entry : KNOWN.entrySet()) { if (message.contains(entry.getKey())) { return entry.getValue(); } } return "unknown -> read the last 'Caused by' line first"; }
public static void main(String[] args) { List<String> failures = List.of( "UnsatisfiedDependencyException: ... No qualifying bean of type 'com.shoplite.category.CategoryService' available", "java.lang.AssertionError: Status expected:<200> but was:<403>", "IllegalArgumentException: Could not resolve placeholder 'DB_PASSWORD' in value \"${DB_PASSWORD}\"", "java.lang.AssertionError: Status expected:<201> but was:<415>", "java.lang.AssertionError: JSON path \"$.name\" expected:<Laptops> but was:<Mobiles>"); for (int i = 0; i < failures.size(); i++) { System.out.println((i + 1) + ". " + diagnose(failures.get(i))); } }}1. the slice lacks a bean -> add @MockitoBean for it, or name only the controller under test
2. security refused -> missing OpenWebMvcTestSecurity (CSRF), wrong role, or jwt() without authorities
3. a property has no value -> the test runs with the wrong profile; add @ActiveProfiles("test")
4. the body was not read as JSON -> .contentType(MediaType.APPLICATION_JSON)
5. unknown -> read the last 'Caused by' line firstWhat this code does
- Most Spring test failures start with one of a few messages; each has a usual cause.
- The program matches a known piece of the message and prints the first thing to try.
- An unknown message gets the general advice: read the last
Caused byline first.
A refusal where you expect success has three usual causes:
- A
@WebMvcTestwithout@Import(OpenWebMvcTestSecurity.class): Boot's default security wants a login (GET gives 401) and a CSRF token (POST gives 403). jwt()without.authorities(...): the caller has onlySCOPE_read, sohasRole(...)refuses with 403.- The wrong role in
@WithMockUser, or a URL that a rule further up theSecurityConfigalready decides.
Failure message, first fix:
- No qualifying bean of type X: add
@MockitoBean X, or use a smaller slice. - Could not resolve placeholder: add
@ActiveProfiles("test"). - Failed to replace DataSource with an embedded database: use
replace = Replace.NONE. - 201 expected, 415 actual: add
.contentType(MediaType.APPLICATION_JSON).
Predict the output
Why the refusal?
Read each test and pick the cause of the refusal.
Round 1 of 2
What is the usual cause?
Finish up
Mark complete & continue
Next: Mini project: test the ShopLite category API