2017-12-31 100 views
1

私はspringbootを学んでおり、簡単なspringbootアプリケーションを作成しました。私はユニットテストを実行するときにmongoDBを埋め込み、アプリケーションの残りの部分については外部mongoDBを使用します。ただし、埋め込み型の代わりに単体テストには外部mongoDBを使用します。 私はPOMに次の2つの依存関係があります。junitテストを作成するには、springbootアプリケーションで埋め込みmongoDBを使用しますか?

<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> 
     <scope>test</scope> 
    </dependency> 

私のプロパティファイルには、以下があります。

# MongoDB properties 
mongo.db.name=person_testDB 
mongo.db.url=localhost 

#external Mongo url 
spring.data.mongodb.uri=mongodb://localhost:27017/personDB 

私が埋め込まれたMongoDBの構成を備えて設定ファイル(MongoDBConfig.java)を持っている:

@EnableMongoRepositories 
public class MongoDBConfig { 

@Value("${mongo.db.url}") 
private String MONGO_DB_URL; 

@Value("${mongo.db.name}") 
private String MONGO_DB_NAME; 

@Bean 
public MongoTemplate mongoTemplate() { 
    MongoClient mongoClient = new MongoClient(MONGO_DB_URL); 
    MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME); 
    return mongoTemplate; 
} 
} 

以下は、私のPersonService.javaクラスです。

@Service 
public class PersonService { 
private static final Logger logger = LoggerFactory.getLogger(PersonService.class);  
@Autowired 
MongoTemplate mongoTemplate;    
public void savePerson(Person person) { 
    String name = person.getName(); 
    String collectionName = name.substring(0, 1); 
     mongoTemplate.save(person, collectionName); 
    }    
} 
次のようにPersonsServiceクラスの

私のユニットテストは、次のとおりです。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {MongoDBConfig.class}) 
@SpringBootTest(classes = PersonService.class) 
@DataMongoTest 
public class PersonServiceTest { 

@Autowired 
PersonService personService;  
MongodForTestsFactory factory; 
MongoClient mongo; 

@Before 
public void setup() throws Exception { 
    factory = MongodForTestsFactory.with(Version.Main.PRODUCTION); 
    mongo = factory.newMongo(); 
} 

@After 
public void teardown() throws Exception { 
    if (factory != null) 
     factory.shutdown(); 
} 

@Test 
public void testSave(){ 
Person person = new Person("Bob Smith " , 25); 
personService.savePerson(person); 
} 
} 

それは私が欲しいものではない外部のMongoDBで正しくコレクション名と文書名を作成します。 unitTestsを組み込みMongoに制限するにはどうすればよいですか?

+0

の可能性のある重複した[やる方法Springブートアプリケーションでの統合テストのためにEmbedded MongDBを構成しますか?](https://stackoverflow.com/questions/31568351/how-do-you-configure-embedded-mongdb-for-integration-testing-in-a-spring -boot-ap) –

答えて

1

代わりに、テストでスプリングブートアプリケーション全体を実行することもできます。この場合、あなたの春のブートアプリケーションが自動的に検出され、MongoDBのを埋め込まれます

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class YourSpringBootApplicationTests { 

08春ブーツでダウンロードされ、開始されます:12:14.676 INFO EmbeddedMongo:42 - 注意:nopreallocが多くで パフォーマンスを傷つけることアプリケーション08:12:14.694 INFO埋め込みMongo:42 - 2017-12-31T08:12:14.693 + 0200 CONTROL [initandlisten] MongoDB 開始:pid = 2246ポート= 52299 08:12:22.005 INFO接続:71 - オープン接続[connectionId {localValue:2、serverValue:2}]を に設定します。localhost:52299

あなたの例の場合では、別のポートで埋め込まれたモンゴを開始するためにコードを変更する可能性:

  1. がapplication.propertiesからプロパティをオーバーライドするために、テスト/ resoures/test.propertiesファイルを追加

    mongo.db.name=person_testDB 
    mongo.db.url=localhost 
    mongo.db.port=12345 
    
  2. MongoDBConfigを変更します。MONGO_DB_PORTフィールドを追加

    @EnableMongoRepositories 
    public class MongoDBConfig { 
        @Value("${mongo.db.url}") 
        private String MONGO_DB_URL; 
    
        @Value(("${mongo.db.port:27017}")) 
        private int MONGO_DB_PORT; 
    
        @Value("${mongo.db.name}") 
        private String MONGO_DB_NAME; 
    
        @Bean 
        public MongoTemplate mongoTemplate() { 
         MongoClient mongoClient = new MongoClient(MONGO_DB_URL, MONGO_DB_PORT); 
         MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME); 
         return mongoTemplate; 
        } 
    } 
    
  3. テストクラスを変更: @DataMongoTest注釈を削除します。それがここで概説です::

    static MongodExecutable mongodExecutable; 
    
    @BeforeClass 
    public static void setup() throws Exception { 
        MongodStarter starter = MongodStarter.getDefaultInstance(); 
        String bindIp = "localhost"; 
        int port = 12345; 
        IMongodConfig mongodConfig = new MongodConfigBuilder() 
          .version(Version.Main.PRODUCTION) 
          .net(new Net(bindIp, port, Network.localhostIsIPv6())) 
          .build(); 
        mongodExecutable = null; 
        try { 
         mongodExecutable = starter.prepare(mongodConfig); 
         mongodExecutable.start(); 
        } catch (Exception e){ 
         // log exception here 
         if (mongodExecutable != null) 
          mongodExecutable.stop(); 
        } 
    } 
    
    @AfterClass 
    public static void teardown() throws Exception { 
        if (mongodExecutable != null) 
         mongodExecutable.stop(); 
    } 
    

もう一つの方法は、MongoRepositoryを使用することで、テスト@Configurationクラスの一部としてモンゴを埋め込まれているinit組み込みのMongoDBインスタンスを起動これは、注釈力How do you configure Embedded MongDB for integration testing in a Spring Boot application?

関連する問題