gpt4 book ai didi

java - Spring MVC Controller 测试 PUT

转载 作者:行者123 更新时间:2023-12-05 05:41:45 25 4
gpt4 key购买 nike

尝试使用 junit5 和 mockito 测试我的 web 层(spring boot、spring mvc)。对 http 方法(get、put、...)的所有其他测试工作正常,但更新。按照代码。

Controller :

@PutMapping(value = "{id}")
public ResponseEntity<?> putOne(@PathVariable Integer id, @Valid @RequestBody Customer customerToUpdate) {
Customer updated = customerService.update(id, customerToUpdate);
return ResponseEntity.ok(updated);
}

服务:

public Customer update(Integer customerId, Customer customerToUpdate) {
Customer customerFound = customerRepository.findById(customerId).orElseThrow(() -> {
throw new CustomerControllerAdvice.MyNotFoundException(customerId.toString());
});

customerToUpdate.setId(customerFound.getId());

return customerRepository.save(customerToUpdate);
}

最后是测试:

static final Customer oneCustomer = Customer.of(3,"john", LocalDate.of(1982, 11, 8));

@Test
void putOneTest() throws Exception {
when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);

mockMvc.perform(put(CUSTOMER_URL + oneCustomer.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(oneCustomer)))
.andDo(print())
.andExpect(jsonPath("$.name").value(oneCustomer.getName()))
.andExpect(jsonPath("$.birthDate").value(oneCustomer.getBirthDate().toString()))
.andExpect(status().isOk());
}

结果:

java.lang.AssertionError: No value at JSON path "$.name"

CustomerService 中的 update(...) 方法只返回 null。无法理解的方式。请指教。

最佳答案

问题是这一行:

when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);

你应该把它改成

when(customerService.update(eq(oneCustomer.getId()), any())).thenReturn(oneCustomer);

因为您的 put 请求正文是 JSON,而不是真正的 Customer,所以 when...thenReturn 语句无法正常工作如你所料。模拟的 customerService 默认返回 null。这就是为什么您得到空响应的原因。因此,您必须更正参数匹配器才能实现。

关于java - Spring MVC Controller 测试 PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72241095/

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