问题是: 当我尝试使用 singleton-testcontainer 时,我的所有测试类首先因断言而失败。 这意味着,即使我在日志中看到我的场景完全成功,断言总是失败。
事实是,当我使用 @Testcontainers 和 @Container 注释时 - 一切都很好。
我的第一堂测试课。
@SpringBootTest(classes = {ContractSpringBootApplication.class})
@ExtendWith({MockitoExtension.class, OutputCaptureExtension.class})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ActiveProfiles("test")
public class UpdateMergeTest extends AbstractTestcontainersTest {
@SpyBean
@Autowired
private TechMergeUpdateRepo techMergeUpdateRepo;
@BeforeEach
void clean() {
techMergeUpdateRepo.deleteAll();
}
我的第二堂测试课。 (做同样的事情,但使用更多的存储库)
@SpringBootTest(classes = {ContractSpringBootApplication.class})
@ExtendWith({MockitoExtension.class, OutputCaptureExtension.class})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ActiveProfiles("test")
public class UpdateEntityTest extends AbstractTestcontainersTest {
@SpyBean
@Autowired
private TechMergeUpdateRepo techMergeUpdateRepo;
@SpyBean
@Autowired
private UpdateEntityRepo updateEntityRepo;
@BeforeEach
void clean() {
techMergeUpdateRepo.deleteAll();
updateEntityRepo.deleteAll();
}
我的“单例”测试容器类。
public abstract class AbstractTestcontainersTest {
private final static String DATABASE_NAME = "test_name";
public static final PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>("postgres:12")
.withReuse(true)
.withDatabaseName(DATABASE_NAME);
static {
postgresContainer.start();
}
@DynamicPropertySource
public static void overrideProps(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgresContainer::getUsername);
registry.add("spring.datasource.password", postgresContainer::getPassword);
registry.add("spring.datasource.driver-class-name", postgresContainer::getDriverClassName);
}
}
但是!
如果我将 AbstractTestcontainersTest 更改为:
@Slf4j
@Testcontainers
public abstract class AbstractTestcontainersTest {
private final static String DATABASE_NAME = "test_name";
@Container
public static final PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>("postgres:12")
.withReuse(true)
.withDatabaseName(DATABASE_NAME);
static {
postgresContainer.start();
}
@DynamicPropertySource
public static void overrideProps(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgresContainer::getUsername);
registry.add("spring.datasource.password", postgresContainer::getPassword);
registry.add("spring.datasource.driver-class-name", postgresContainer::getDriverClassName);
}
}
它将开始正常工作。
我检查了日志输出。 感觉问题出在 Spring 测试“欠载”的某个地方,在测试类中,从第二个开始。 我检查了日志 - 我的“场景”已完全完成并且工作正常,但断言正在下降
我检查了日志输出。 感觉问题出在 Spring 测试“欠载”的某个地方,在测试类中,从第二个开始。
问题出在使用 @SpyBean 注释。
因为在单例测试容器的情况下,上下文没有完全重新引发。 断言时,第一个类之后的所有@SpyBean都指向Proxy,无需显式代理。
将 @SpyBean 注解的注入移至基类(AbstractTestcontainersTest)解决了问题。