java - 当预期为 404 时,Spring Boot 控制器测试返回 200
问题描述
我正在尝试测试控制器层。在这种情况下,通过 id 查找客户。我有一个通过测试,它工作正常并返回200
状态代码。现在,我想要一个失败的测试用例场景。所以当我得到 /customers/1
测试应该失败并返回一个404
,但它正在返回200
。使用 Junit5, Spring-boot:2.5.3
@WebMvcTest
public class CustomerControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CustomerService customerService;
@Test
@DisplayName("GET /customers/1 -Failure")
void findCustomerByIdShouldReturn_404() throws Exception {
when(customerService.findById(1L)).thenReturn(Optional.empty());
RequestBuilder requestBuilder= MockMvcRequestBuilders.get("/customers/{id}",1);
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound()).andReturn();
}
}
错误:
HTTP Method = GET
Request URI = /customers/1
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.prabhakar.customer.controller.CustomerController
Method = com.prabhakar.customer.controller.CustomerController#findCustomerById(Long)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = null
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<404> but was:<200>
Expected :404
Actual :200
这是我的控制器和服务类。
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping(path = "/customers/{id}")
public Optional<Customer> findCustomerById(@PathVariable("id") Long id){
return customerService.findById(id);
}
}
@Service
public class CustomerService {
@Autowired
private CustomerRepository customerRepository;
public Optional<Customer> findById(Long id) {
return customerRepository.findById(id);
}
}
解决方案
您的控制器没有您希望测试的逻辑。这是您的控制器应如何实现以按照您希望的方式运行
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping(path = "/customers/{id}")
public ResponseEntity<Customer> findCustomerById(@PathVariable("id") Long id){
Optional<Customer> optCust = customerService.findById(id);
if (optCust.isPresent()){
return ResponseEntity.ok(optCust.get());
} else {
return ResponseEntity.notFound().build()
}
}
}
推荐阅读
- android - 如何使用应用内更新库防止内存泄漏
- c - 在C中实现结构的动态分配
- javascript - 如何创建具有相同标签名称的嵌套内联印迹?
- omnet++ - 如何用LTE基站创建网络并动态创建/删除汽车雾节点?
- angularjs - Http Post Angularjs通过Web API导致内部服务器错误
- tensorflow - 为什么我的结果仍然无法重现?
- sql - 在集合中查找缺失的子集
- swift - 如何判断 EKEvent 实例是否被拒绝?
- javascript - 加载资源失败:服务器响应状态为 409
- android - 如何观察 LiveData
在 kotlin 中使用 android 分页