春季MVC控制器测试

发布于 2025-01-28 16:43:57 字数 1644 浏览 4 评论 0原文

尝试使用Junit5和Mockito测试我的网络层(Spring Boot,Spring MVC)。 HTTP方法(获取,put,...)的所有其他测试都可以正常工作,但更新。 遵循代码。

控制器:

@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"

update(...)方法在客户服务返回仅null中。无法理解方式。请建议。

Trying to test my web tier (spring boot, spring mvc) with junit5 and mockito. All other tests on http methods (get, put, ...) are working fine but the update.
Following the code.

Controller:

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

Service:

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);
}

Finally the test:

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

Result:

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

update(...) method in CustomerService return just null. Can't understand way. Please advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

避讳 2025-02-04 16:43:57

问题是以下行:

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

您应该将其更改为,

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

因为您的PUT请求主体是JSON,而不是真实的客户当...代码>语句无法正常工作。模拟的CustomerService默认情况下返回零。这就是为什么您收到空的回复的原因。因此,您必须纠正参数匹配器才能实现。

The problem is this line:

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

You should change it to

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

Because your put request body is a JSON, not a real Customer, the when...thenReturn statement didn't work well as you expected. The mocked customerService returns a null by default. This is why you got a empty response. So you must to correct the argument matcher to make it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文