try 用junit5和mockito测试我的web层(spring boot、spring mvc).http方法的所有其他测试(get、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"

更新(…)CustomerService中的方法仅返回null.我不明白怎么回事.请给出建议.

推荐答案

问题在于这一行:

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

你应该把它改成

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

因为你的put请求主体是JSON,而不是真正的Customer,所以when...thenReturn语句并没有像你预期的那样好用.mocked customerService默认返回空值.这就是为什么你得到了一个空洞的回答.因此,你必须纠正参数匹配器,使其正确.

Java相关问答推荐

参数值[...]与预期类型java.util.Date不匹配

neo4j java驱动程序是否会在错误发生时自动回滚事务?

为什么BasicComboBoxRenderer在文本不存在或文本为空的情况下设置两次文本?

根据对象和值的参数将映射<;T、值&>转换为列表<;T&>

无法在WebSocket onMessage中捕获错误

如何判断一个矩阵是否为有框矩阵?

当我已经安装了其他版本的Java时,如何在Mac OSX 14.3.1上安装Java 6?

具有多种令牌类型和段的复杂Java 17正则表达式

名称冲突具有相同的擦除

使用Mockito进行的Junit测试失败

呈现文本和四舍五入矩形时出现的JavaFX窗格白色瑕疵

如何在ApachePOI中将图像添加到工作表的页眉?

有没有办法知道在合并中执行了什么操作?

记录是类的语法糖吗?

为什么我不能建立输入/输出流?Java ServerSocket

如何使用jooq更新记录?

为什么没有加载java.se模块?

Java中的一个错误';s stdlib SocksSocketImpl?

找不到 jar 文件系统提供程序try 使用 jdeps 和 jlink 创建收缩 Java 映像来运行 Minecraft

Java ModbusRTU写寄存器