【发布时间】:2025-12-14 05:55:02
【问题描述】:
我正在用 Spring boot 和数据做一个简单的示例项目。
@Configuration
public class MongoConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoConfig.class);
@Value("${mongo.uri}")
private String mongoUri;
public @Bean MongoClient mongoClient() {
LOGGER.info(" creating connection with mongodb with uri [{}] ", mongoUri);
return MongoClients.create(mongoUri);
}
}
这工作正常并在启动时连接到 mongo。但是,测试也会在自动扫描中发现这一点。确保 mongo 配置被排除在测试之外的最佳做法是什么?
如果我将 @WebMvcTest 添加到测试中,它会起作用。但并非所有测试都是 mvc 测试。我可能正在测试一个实用程序类。
如果我尝试使用配置文件,它会给我一个错误java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes: ...MongoConfig
@SpringBootTest
@ActiveProfiles("test")
class ApplicationTests {
@Test
void contextLoads() {
}
}
请告诉我一个可重复的练习,因为我将在所有测试中使用它。
【问题讨论】:
-
阅读并关注这篇文章,你会很好:baeldung.com/spring-boot-exclude-auto-configuration-test
标签: spring unit-testing spring-data spring-data-mongodb