【问题标题】:Springboot embedded mongo testSpring Boot 嵌入式 mongodb 测试
【发布时间】:2018-10-09 18:04:36
【问题描述】:

我正在尝试使用 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 应用程序

@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 开箱即用吗?

【问题讨论】:

    标签: java mongodb spring-boot embedded-database


    【解决方案1】:
    • 使用 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()) 
          }
      }
      

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 2016-08-26
      • 1970-01-01
      • 2021-03-17
      • 2019-10-26
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多