I am trying to test a simple SpringBoot application with Embedded Mongo but my repository is getting set to null
. Can anyone spot what I am missing?
//Controller:
@RestController
public class MyController {
@Autowired
private MyRepository myRepo;
public MyController() {
}
@RequestMapping(method= RequestMethod.GET, value="/test")
public Iterable<Test> findAll() {
return myRepo.findAll();
}
}
//Empty repository interface
public interface MyRepository extends CrudRepository< Test, String> {
}
//Spring Boot Application
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
//Integration test
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyIntegrationTest {
MockMvc mockMvc;
MyController controller;
@Autowired
MyRepository myRepo;
@Before
public void setup() {
controller = new MyController();
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void testing() throws Exception {
MockHttpServletRequestBuilder request = get("/test").contentType(APPLICATION_JSON);
HttpServletResponse response = mockMvc.perform(request).andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
}
//Dependencies in gradle file:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile "de.flapdoodle.embed:de.flapdoodle.embed.mongo:1.50.5"
testCompile group: 'cz.jirutka.spring', name: 'embedmongo-spring', version: '1.3.1'
}
myRepo.findAll()
is null
- how can this get set? Will it work out of the box with embedded mongo?
Use MongoRepository
instead of CrudRepository
when working with MongoDB.
Your integration test is for verifying end-to-end behavior of the system, so there is no need to include the controller or repository in your test class. Try to use the following:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyIntegrationTest {
@Autowired
MockMvc mockMvc;
@Test
public void testing() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/test"))
.andExpect(MockMvcResultMatchers.status().isOk())
}
}