问题:
如果DB设计有自增ID时,Repository层测试在某些环境下因为并行执行可能会遇到乱序的问题,导致某些测试偶尔通过、偶尔失败;
解决方案:
1、注入:EntityManager�
2、在 BeforeEach 阶段重置表的自增ID
参考代码:
@SpringBootTest
@ActiveProfiles("test")
@Transactional
class XxxRepositoryTest {
@Autowired
private EntityManager entityManager;
@BeforeEach
void resetAutoId() {
String sql = "ALTER TABLE table_name ALTER COLUMN id RESTART WITH 1";
entityManager.createNativeQuery(sql).executeUpdate();
}
}