我已经创建了junit 5注释来在每次使用flyway进行测试之前清理和迁移我的数据库。这是参考:博客
在我的申请中,我还安排了工作。在集成测试(使用@SpringBootTest)中,当调度程序作业运行时,它会失败,因为flyway清除了数据库并且调度作业不知道它。对于每个数据库调用,它都会显示:“o.h.engine.jdbc.spi.SqlExceptionHelper:错误:关系“test_table”不存在”
我该如何解决这个问题?
这是注释:
@Slf4j
public class ClearDatabaseBeforeEachCallback implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
log.info("Clear database before each request :'{}'", context.getDisplayName());
clearFlyway(context);
}
private void clearFlyway(ExtensionContext context) {
Flyway flyway = SpringExtension.getApplicationContext(context)
.getBean(Flyway.class);
flyway.clean();
flyway.migrate();
}
}
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(ClearDatabaseBeforeEachCallback.class)
@TestPropertySource(properties = "spring.flyway.clean-disabled=false")
public @interface ClearDatabaseBeforeEach {
}
这是示例测试用例:
@ClearDatabaseBeforeEach
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseSpringBootTest extends BaseIntegrationTest {
}
public class AppFlowTest extends BaseSpringBootTest {
@Test
void anyTest() {
// any test that can longer than the first scheduled runner
// while the test runs, scheduled job is called in another thread
// or scheduled job is called, just after the first test is finished and just before the second test case is started
}
}
也许你可以在 Flyway 和 TestCase 之间使用
lock
。
可以使用
CountDownLatch
类。
一些代码示例,可能无法执行。
public class ClearDatabaseBeforeEachCallback implements BeforeEachCallback {
public static CountDownLatch latch;
@Override
public void beforeEach(ExtensionContext context) throws Exception {
latch = new CountDownLatch(1);
log.info("Clear database before each request :'{}'", context.getDisplayName());
clearFlyway(context);
latch.countDown();
}
}
然后在您的测试代码中添加
wait
:
public class AppFlowTest extends BaseSpringBootTest {
@Test
void anyTest() {
ClearDatabaseBeforeEachCallback.latch.await();
//your test code
}
}
但这是一个非常原始的想法,你可以进一步尝试。