如果由于任何原因无法使用它,请继续阅读。
测试类别:
@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;@Configurationpublic 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>



