Mockito,我在控制器中测试 Post 方法时做错了什么?

Mockito, what am I doing wrong testing Post method in Controller?

这是我的测试

        @Test
    @WithMockUser(authorities = "ADMIN")
void shouldCreateRestaurant_whenPost() throws Exception {
        // when
        mockMvc.perform(
                post("/restaurant/admin/")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(this.objectMapper.writeValueAsString(RESTAURANT_CREATION_DOMINOS)));
        // then
        Mockito.verify(restaurantService, times(1)).create(RESTAURANT_CREATION_DOMINOS);
    }

它失败了,因为它比较对象和=。第一个对象 RestaurantCreationDTO@5980fa73,第二个 RestaurantCreationDTO@15a8cebd。 但是我如何才能确保使用有效参数调用 restaurantService?

您有两个选择:

首先 - 如果足以检查服务调用中的对象是否确实是 RestaurantCreationDTO:

Mockito.verify(restaurantService, times(1)).create(any(RestaurantCreationDTO.class));

其次 - 如果你真的想检查服务调用中的对象内容

在你的测试中class

@Captor
ArgumentCaptor<RestaurantCreationDTO> restaurantCreationDtoCaptor;

在你的测试方法中

Mockito.verify(restaurantService, times(1)).create(restaurantCreationDtoCaptor.capture());
assertThat(restaurantCreationDtoCaptor.getValue()).isEqual(RESTAURANT_CREATION_DOMINOS)