
[英]Integration Tests fail to connect, Manual Browser Test succeeds with Java RESTful Web Service with SpringBoot/Jsoup Integration Test
[英]springboot Integration test fail when using jsonPath
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我在 springboot 中进行了集成测试,我试图在我的 controller 中测试一个 get 方法。该方法在 postman 中工作。但是它在测试中失败,找不到 Json 路径。
测试的controller方法:
@GetMapping("/product/{id}")
public Product getproduct(@PathVariable int id){
return productRepository.findById(id).orElse(null);
}
我的测试代码:
@ExtendWith(SpringExtension.class)
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private ProductRepository productRepository;
@MockBean
private CustomerRepository customerRepository;
@Test
void getproduct() throws Exception {
/* RequestBuilder request= MockMvcRequestBuilders.;*/
mvc.perform(get("/product/{pid}","201")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.productName").value("Mobile"));
}
}
结果为 postman:
{
"pid": 201,
"productName": "Mobile",
"quantity": 1,
"price": 20000
}
错误信息:
java.lang.AssertionError: No value at JSON path "$.productName"
正如 Marko在这里提到的,jsonPath可能将 json 正文解释为一个列表,因此您可以尝试解决 json 正文中的第一个 object:
.andExpect(jsonPath("$[0].productName").value("Mobile"));
您正在使用@MockBean
这意味着您使用的是模拟存储库而不是连接到数据库的真实存储库。 由于您没有在模拟上注册任何行为,因此它将执行其默认行为,即对于Optional
返回一个空的Optional
。 这导致null
被返回,因此没有正文。
我建议将您的 controller 重写为以下内容。
@GetMapping("/product/{id}")
public ResponseEntity<Product> getproduct(@PathVariable int id){
return ResponseEntity.of(productRepository.findById(id));
}
这可能会使您的测试在 OK 断言上失败,因为它现在将返回 404(未找到)。
要修复您的测试,请在模拟存储库上注册相同的行为。
@Test
void getproduct() throws Exception {
Product p = /// Create some product
when(productRepository.findById(201)).thenReturn(Optional.of(p));
mvc.perform(get("/product/{pid}","201")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.productName").value("Mobile"));
}
这将创建您想要的行为并返回产品,然后您可以声明该产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.