协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
insurance-testing【开发与工程】Detailed testing standards for persistence, service, and controller layers
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Use this skill when creating or modifying tests in this project.
@WebMvcTest + MockMvc.@SpringBootTest or @DataJpaTest with in-memory DB.Applies to repository/integration-style tests.
@Transactional + @Rollback) to avoid side effects.src/test/resources/sql/ + @Sql).create/update/delete), call EntityManager.flush() before assertions.JdbcTestUtils.countRowsInTableJdbcTestUtils.countRowsInTableWhereInstanceProvider.<Entity>RepositoryTest.@Transactional
@Rollback
@SpringBootTest
class UserRepositoryTest {
private static final String EMAIL = "test@example.com";
@PersistenceContext
private EntityManager em;
@Autowired
private UserRepository userRepository;
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
@BeforeEach
void setUp() {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Test
void testCreate() {
// Arrange
int before = JdbcTestUtils.countRowsInTable(jdbcTemplate, "users");
// Act
User user = userRepository.create(EMAIL, "secret", "John", "Doe");
em.flush();
// Assert
assertEquals(before + 1, JdbcTestUtils.countRowsInTable(jdbcTemplate, "users"));
assertNotNull(user);
}
}
Pure unit tests (no Spring context).
@ExtendWith(MockitoExtension.class)).@Mock.@InjectMocks.assertThrows for failure scenarios.<Service>ImplTest.@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
private static final long USER_ID = 1L;
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepository userRepository;
@Test
void testFindByIdExistingUser() {
// Arrange
when(userRepository.findById(USER_ID)).thenReturn(Optional.of(new User()));
// Act
Optional<User> result = userService.findById(USER_ID);
// Assert
assertTrue(result.isPresent());
}
@Test
void testFindByIdNonExisting() {
// Arrange
when(userRepository.findById(anyLong())).thenReturn(Optional.empty());
// Act
Optional<User> result = userService.findById(1L);
// Assert
assertFalse(result.isPresent());
}
}
Use Mockito helpers or slice tests based on scope.
@WebMvcTest + MockMvc.<Entity>ControllerTest.private User createUserWithId(String email, Long id) throws Exception {
User user = new User(email);
Field idField = User.class.getDeclaredField("id");
idField.setAccessible(true);
idField.set(user, id);
return user;
}
Keep small helper methods (createUserWithId, createMockAuthentication, etc.) inside the test class to reduce
duplication and improve readability.