Springboot嵌入式mongo测试

时间:2018-04-29 13:21:14

标签: java mongodb spring-boot embedded-database

我正在尝试使用Embedded Mongo测试一个简单的SpringBoot应用程序,但我的存储库已设置为null。谁能发现我所缺少的东西?

//控制器:

@RestController
public class MyController {

    @Autowired
    private MyRepository myRepo;

    public MyController() {
    }

    @RequestMapping(method= RequestMethod.GET, value="/test")
    public Iterable<Test> findAll() {
        return myRepo.findAll();
    }
}

//清空存储库界面

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);
    }
}

//集成测试

@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());
    }

// gradle文件中的依赖项:

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()null - 这怎么设置?是否可以开箱即用嵌入式mongo?

1 个答案:

答案 0 :(得分:2)

  • 使用MongoDB时,请使用MongoRepository代替CrudRepository

  • 您的集成测试用于验证系统的端到端行为,因此无需在测试类中包含控制器或存储库。尝试使用以下内容:

    @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()) 
        }
    }