2016-11-13 9 views
0

私は、次のモデルがあります:developmentデータベースが含まれているcustomersのコレクションが含まれていスイッチ - Javaの春ブーツ

import java.util.List; 

import org.springframework.data.mongodb.repository.MongoRepository; 

public interface CustomerRepository extends MongoRepository<Customer, String> { 

    public Customer findByFirstName(String firstName); 
    public List<Customer> findByLastName(String lastName); 

} 

import org.springframework.data.annotation.Id; 

@Document 
public class Customer { 

    @Id 
    public String id; 

    public String firstName; 
    public String lastName; 


    public Customer() {} 

    public Customer(String firstName, String lastName) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
    } 

    @Override 
    public String toString() { 
     return String.format(
       "Customer[id=%s, firstName='%s', lastName='%s']", 
       id, firstName, lastName); 
    } 

} 

そして、次のリポジトリを実データ - 実際の顧客に関する情報。私はもちろん

@RunWith(SpringRunner.class) 
@SpringBootTest 
@ContextConfiguration(classes = {CustomerTest.class}) 
public class CustomerTest { 

    @Autowired 
    private CustomerRepository repository; 

    @Before 
    public void setUp() throws Exception { 
      // I want to delete the test database, not the production one 
      repository.deleteAll(); 
    } 

    @Test 
    public void testCreateCustomer() { 

     // save a couple of customers 
     repository.save(new Customer("Alice", "Smith")); 
     repository.save(new Customer("Bob", "Smith")); 

     // fetch all customers 
     System.out.println("Customers found with findAll():"); 
     System.out.println("-------------------------------"); 
     for (Customer customer : repository.findAll()) { 
      System.out.println(customer); 
     } 
     System.out.println(); 

     // fetch an individual customer 
     System.out.println("Customer found with  findByFirstName('Alice'):"); 
     System.out.println("--------------------------------"); 
     System.out.println(repository.findByFirstName("Alice")); 

     System.out.println("Customers found with findByLastName('Smith'):"); 
     System.out.println("--------------------------------"); 
     for (Customer customer : repository.findByLastName("Smith")) { 
      System.out.println(customer); 
     } 
    }  
} 

ユニットテストを実行しながら、私はproductiontestデータベース間で切り替えることができますどのようにSpringMongoConfig.java

@Configuration 
@PropertySource(value={"classpath:application.properties"}) 
public class SpringMongoConfig extends AbstractMongoConfiguration { 

    @Value("${spring.data.mongodb.host}") 
    private String host; 

    @Value("${spring.data.mongodb.port}") 
    private Integer port; 

    @Value("${spring.data.mongodb.database}") 
    private String database; 

    public @Bean 
    MongoDbFactory mongoDbFactory() throws Exception { 
     return new SimpleMongoDbFactory(new MongoClient(this.host + ":" + this.port), database); 
    } 

    public @Bean 
    MongoTemplate mongoTemplate() throws Exception { 
     MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory()), 
       new MongoMappingContext()); 
     converter.setMapKeyDotReplacement("\\+"); 

     MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter); 

     return mongoTemplate; 

    } 

    @Override 
    protected String getDatabaseName() { 
     return this.database; 
    } 

    @Override 
    public Mongo mongo() throws Exception { 
     return new MongoClient(this.host, this.port); 
    } 
} 

: はTDDの大ファンとして、私は以下のユニットテストを作成しましたか?

+0

注:MongoDBとは何か関係がありますか?これ以外にも、環境変数を使用することができます。 –

答えて

2

私は個人的にテスト用に組み込みデータベースを使用します。あなたは春のブートプロファイルを使用することができ、開発や生産などの他のプロファイルについて

package com.backend.repository; 

import com.backend.configuration.MongoConfiguration; 
import org.junit.runner.RunWith; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MongoConfiguration.class) 
public class CustomerRepositoryTest { 

} 

docを参照)か、Mavenのプロファイルを使用することができます:あなたは、テストクラスではFakeMongo

package com.backend.configuration; 

import com.github.fakemongo.Fongo; 
import com.mongodb.Mongo; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.data.mongodb.config.AbstractMongoConfiguration; 
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 

@Configuration 
@EnableMongoRepositories(basePackages = "com.backend.repository") 
public class MongoConfiguration extends AbstractMongoConfiguration { 

    private static final String DB_NAME = "test"; 

    @Override 
    protected String getDatabaseName() { 
    return DB_NAME; 
    } 

    @Override 
    @Bean 
    public Mongo mongo() { 
    return new Fongo(getDatabaseName()).getMongo(); 
    } 

    @Override 
    protected String getMappingBasePackage() { 
    return "com.backend.domain"; 
    } 
} 

を使用することができます でapplication.propertiesこのプロパティ[email protected]@を追加使用プロファイルにaccroding pom.xmlでそれを定義します。

<profile> 
     <id>dev</id> 
     <activation> 
      <activeByDefault>true</activeByDefault> 
     </activation> 
     <properties> 
      <mongo.host>localhost</mongo.host> 
     </properties> 
    </profile> 
    <profile> 
     <id>prod</id> 
     <properties> 
      <mongo.host>mongo</mongo.host> 
     </properties> 
    </profile> 
2

それを行うための最も簡単な方法は、ちょうどあなたのテストで所望の特性をオーバーライドしている:あなたはBeanを再定義する必要がある場合には

@RunWith(SpringRunner.class) 
@SpringBootTest(properties = { 
    "spring.data.mongodb.database=test_db" 
}) 
@ContextConfiguration(classes = {CustomerTest.class}) 
public class CustomerTest { 

- 実装fongoメモリ内のインスタンスで使用するために、あなたはCustomTestConfigを作成し、それを追加することができますあなたのテストに:

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = TestConfig.class) 
@ContextConfiguration(classes = {CustomTestConfig.class}) 
public class CustomerTest { 
0

オンラインデータベースまたはテストデータベースを切り替える場合は、単体テスト時にテストデータベースを使用します。あなたのデータソースの設定で@Conditional注釈を使用することができます。ここ は方法です:

  1. ConditionalをIMPLするクラスを追加します。

@Conditional(Online.class) @Component class OnlineDatasrouceConfig{ }

yml設定を読み込むことで、オンライン条件の一つは、テストの他には、condition.Youはちょうど

  • は、データソースの設定にそれらの条件を追加し、この2つの条件クラスをIMPLすることができます

    @Conditional(OnTest.class) @Component class TestDatasrouceConfig{ }

    次に、conditionalがtrueの場合にのみspringがBeanを作成します。あなたはユニットテストを実行しているとき、テスト・データベースを切り替えるには他のいくつかの方法があり、 http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-condition-annotations

    そして:ここ

    は、条件の文書です。 テストクラスに@ActiveProfile("test")を追加します。 springはtest.ymlを使ってこのテストクラスを初期化します。そして、あなたはテストデータベースの設定をtest.ymlに入れておく必要があります(私はこの方法を使用しています)