Skip to content

Instantly share code, notes, and snippets.

@ringoluo
Created February 7, 2015 15:54
Show Gist options
  • Save ringoluo/32cb5c872e4854332e6d to your computer and use it in GitHub Desktop.
Save ringoluo/32cb5c872e4854332e6d to your computer and use it in GitHub Desktop.
spring boot + spring data mongoldb + nosqlunit-mongodb
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ActiveProfiles("test") // activate test configuration
public class AccountRepositoryTest {
private @Autowired AccountRepository accountRepo;
private @Autowired ApplicationContext applicationContext; // !!important to have it here
public @Rule MongoDbRule mongoDbRule = MongoDbRuleBuilder.newMongoDbRule().defaultSpringMongoDb(
"spring-dbname"); // name should match spring mongodb name
@Test
@UsingDataSet(locations = "initialData.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) // database initialized from initalData.json
@ShouldMatchDataSet(location = "expectedData.json")
public void test1() {
accountRepo.save(new Account("luochun", "secret"));
long count = accountRepo.count();
assertThat(count, equalTo(1L)); //!! test case is isolated
}
@Test
@UsingDataSet(locations = "initialData.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) // database initialized from initalData.json
@ShouldMatchDataSet(location = "expectedData.json")
public void test2() {
accountRepo.save(new Account("luochun", "secret"));
long count = accountRepo.count();
assertThat(count, equalTo(1L)); //!! test case is isolated
}
}
...
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-mongodb")
compile("org.projectlombok:lombok:1.14.8")
compile("com.google.guava:guava:18.0")
compile("org.apache.commons:commons-lang3:3.3.2")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("com.lordofthejars:nosqlunit-mongodb:0.8.0")
}
...
{
"account": [
{"username":"luochun","password":"secret"}
]
}
{
"account": []
}
@Configuration
@Profile("test") // def
public class MongoTestConfiguration {
public @Bean Mongo mongo() {
return new Fongo("testdb").getMongo();
}
public @Bean MongoTemplate mongoTemplate() {
MongoTemplate mongoTemplate = new MongoTemplate(mongo(), "spring-dbname");
return mongoTemplate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment