我有一个相当简单的Spring Boot应用程序,它暴露了一个小的REST API并从MongoDB实例中检索数据。对MongoDB实例的查询通过基于Spring Data的存储库进行。以下代码的一些关键部分。
// Main application class
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
@Import(MongoConfig.class)
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
// Product repository with Spring data
public interface ProductRepository extends MongoRepository<Product, String> {
Page<Product> findAll(Pageable pageable);
Optional<Product> findByLineNumber(String lineNumber);
}
// Configuration for "live" connections
@Configuration
public class MongoConfig {
@Value("${product.mongo.host}")
private String mongoHost;
@Value("${product.mongo.port}")
private String mongoPort;
@Value("${product.mongo.database}")
private String mongoDatabase;
@Bean(name="mongoClient")
public MongoClient mongoClient() throws IOException {
return new MongoClient(mongoHost, Integer.parseInt(mongoPort));
}
@Autowired
@Bean(name="mongoDbFactory")
public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
return new SimpleMongoDbFactory(mongoClient, mongoDatabase);
}
@Autowired
@Bean(name="mongoTemplate")
public MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, mongoDatabase);
}
}
@Configuration
@EnableMongoRepositories
public class EmbeddedMongoConfig {
private static final String DB_NAME = "integrationTest";
private static final int DB_PORT = 12345;
private static final String DB_HOST = "localhost";
private static final String DB_COLLECTION = "products";
private MongodExecutable mongodExecutable = null;
@Bean(name="mongoClient")
public MongoClient mongoClient() throws IOException {
// Lots of calls here to de.flapdoodle.embed.mongo code base to
// create an embedded db and insert some JSON data
}
@Autowired
@Bean(name="mongoDbFactory")
public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
return new SimpleMongoDbFactory(mongoClient, DB_NAME);
}
@Autowired
@Bean(name="mongoTemplate")
public MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, DB_NAME);
}
@PreDestroy
public void shutdownEmbeddedMongoDB() {
if (this.mongodExecutable != null) {
this.mongodExecutable.stop();
}
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestProductApplication.class)
@IntegrationTest
@WebAppConfiguration
public class WtrProductApplicationTests {
@Test
public void contextLoads() {
// Tests empty for now
}
}
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
@Import(EmbeddedMongoConfig.class)
public class TestProductApplication {
public static void main(String[] args) {
SpringApplication.run(TestProductApplication.class, args);
}
}
所以这里的想法是让集成测试(目前为空)连接到嵌入式mongo实例而不是“实时”实例。但是,它不起作用。我可以看到测试连接到Mongo的“实时”实例,如果我关闭它,那么构建就会失败,因为它仍然试图连接到Mongo的实例。有人知道为什么吗?如何让测试连接到嵌入式实例?
答案 0 :(得分:34)
从Spring Boot 1.3开始,有一个EmbeddedMongoAutoConfiguration
类开箱即用。这意味着你根本不必创建配置文件,如果你想改变你仍然可以做的事情。
添加了嵌入式MongoDB的自动配置。依赖 de.flapdoodle.embed:de.flapdoodle.embed.mongo 就是开始使用所需的全部内容。可以通过application.properties控制配置,例如要使用的Mongo版本。有关详细信息,请参阅文档。 (Spring Boot Release Notes)
必须添加到application.properties文件的最基本和最重要的配置是
spring.data.mongodb.port=0
(0表示将从免费中随机选择它)
有关详情,请查看:Spring Boot Docs MongoDb
答案 1 :(得分:17)
编辑:使用EmbeddedMongoAutoConfiguration
,查看magiccrafter's answer有关Spring Boot 1.3+的内容。
如果您因任何原因无法使用它,请继续阅读。
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {
Application.class,
TestMongoConfig.class // <--- Don't forget THIS
})
public class GameRepositoryTest {
@Autowired
private GameRepository gameRepository;
@Test
public void shouldCreateGame() {
Game game = new Game(null, "Far Cry 3");
Game gameCreated = gameRepository.save(game);
assertEquals(gameCreated.getGameId(), gameCreated.getGameId());
assertEquals(game.getName(), gameCreated.getName());
}
}
简单的MongoDB存储库:
public interface GameRepository extends MongoRepository<Game, String> {
Game findByName(String name);
}
MongoDB测试配置:
import com.mongodb.Mongo;
import com.mongodb.MongoClientOptions;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class TestMongoConfig {
@Autowired
private MongoProperties properties;
@Autowired(required = false)
private MongoClientOptions options;
@Bean(destroyMethod = "close")
public Mongo mongo(MongodProcess mongodProcess) throws IOException {
Net net = mongodProcess.getConfig().net();
properties.setHost(net.getServerAddress().getHostName());
properties.setPort(net.getPort());
return properties.createMongoClient(this.options);
}
@Bean(destroyMethod = "stop")
public MongodProcess mongodProcess(MongodExecutable mongodExecutable) throws IOException {
return mongodExecutable.start();
}
@Bean(destroyMethod = "stop")
public MongodExecutable mongodExecutable(MongodStarter mongodStarter, IMongodConfig iMongodConfig) throws IOException {
return mongodStarter.prepare(iMongodConfig);
}
@Bean
public IMongodConfig mongodConfig() throws IOException {
return new MongodConfigBuilder().version(Version.Main.PRODUCTION).build();
}
@Bean
public MongodStarter mongodStarter() {
return MongodStarter.getDefaultInstance();
}
}
的pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>1.48.0</version>
<scope>test</scope>
</dependency>
答案 2 :(得分:5)
我将完成之前的回答
<强>的pom.xml 强>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>${embedded-mongo.version}</version>
</dependency>
<强> MongoConfig 强>
@Configuration
@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class })
public class MongoConfig{
}
答案 3 :(得分:5)
在1.5.7版本中使用:
@RunWith(SpringRunner.class)
@DataMongoTest
public class UserRepositoryTests {
@Autowired
UserRepository repository;
@Before
public void setUp() {
User user = new User();
user.setName("test");
repository.save(user);
}
@Test
public void findByName() {
List<User> result = repository.findByName("test");
assertThat(result).hasSize(1).extracting("name").contains("test");
}
}
并且
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
</dependency>
答案 4 :(得分:3)
确保您明确使用@ComponentScan
。默认情况下,
如果未定义特定包,则会发生扫描 带有此注释的类的包。 (@ComponentScan Javadoc)
因此,如果您的TestProductApplication
和ProductApplication
配置都在同一个软件包中,则Spring可能会对您的ProductApplication
配置进行组件扫描并使用它。
此外,我建议将测试mongo bean放入“测试”或“本地”配置文件中,并使用测试类中的@ActiveProfiles注释来启用测试/本地配置文件。