gpt4 book ai didi

java - Springboot嵌入mongo测试

转载 作者:行者123 更新时间:2023-12-02 02:10:39 24 4
gpt4 key购买 nike

我正在尝试使用嵌入式 Mongo 测试一个简单的 SpringBoot 应用程序,但我的存储库被设置为 null。谁能发现我缺少什么吗?

// Controller :

@RestController
public class MyController {

@Autowired
private MyRepository myRepo;

public MyController() {
}

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

//清空仓库接口(interface)

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() is null - 如何设置?它可以通过嵌入式 mongo 开箱即用吗?

最佳答案

  • 使用 MongoDB 时,使用 MongoRepository 而不是 CrudRepository

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

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

关于java - Springboot嵌入mongo测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50087033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com