Skill: Testing (spring-mvc-demo)
Service tests (plain JUnit, no Spring)
class ProductServiceTest {
private ProductService service;
@BeforeEach
void setUp() {
service = new ProductService(); // fresh store per test
}
}
Controller tests (`@WebMvcTest`)
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mockMvc;
@Autowired ObjectMapper objectMapper;
@MockBean ProductService productService;
}
Rules
- Service tests: no Spring context,
new ProductService()in@BeforeEach. - Controller tests:
@WebMvcTestonly — no@SpringBootTest. - Mock the service with
@MockBean, never instantiate it in controller tests. - Assert
$.codein error responses — never$.message. - Use
willThrow(new XxxException(id)).given(service).method(id)for void methods.
Test naming
method_condition_expectedResult
Design Constraints
- Do not use
@SpringBootTest—@WebMvcTestfor controllers, plain JUnit for services - Do not assert on
$.messagetext — assert on$.codeonly - Do not share service state between tests — always
new ProductService()in@BeforeEach