【问题标题】:Why mocked mvc test fails with exception when service is mocked?为什么在模拟服务时模拟 mvc 测试失败并出现异常?
【发布时间】:2020-10-24 22:02:04
【问题描述】:

我不明白为什么这个测试失败并出现异常? 服务类被嘲笑...

@Autowired
private MockMvc mockMvc;

@MockBean
private InventoryService inventoryService;


private List<InventoryDTO> inventoryList;

@BeforeEach
void setup() {
    ...
}

@Test
@DisplayName("POST /inventory test - status 200")
@WithMockUser(roles = {"PUBLISHER", "USER"})
void addItem() throws Exception {

    doReturn(inventoryList.get(0)).when(inventoryService).add(any());

    mockMvc.perform(
            MockMvcRequestBuilders.post("/inventory")
                    .content(asJsonString(inventoryList.get(0)))
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isOk())
            .andExpect(content().json("{'name':'test1','description':'test-1-description','price':10}"))
            .andReturn();
}

这是经过测试的控制器:

@RestController
public class InventoryController {

    private final InventoryService inventoryService;

    public InventoryController(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    @GetMapping("/inventory")
    @ResponseBody public List<InventoryDTO> allInventory(){
        return inventoryService.findAll();
    }

    @PostMapping("/inventory")
    @ResponseBody public InventoryDTO addInventory(@RequestBody InventoryDTO inventoryDTO){
        return inventoryService.add(inventoryDTO);
    }

还有例外:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.teamcompetencymatrix.www.dto.AuditDTO]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.teamcompetencymatrix.www.dto.AuditDTO` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 1, column: 72] (through reference chain: com.teamcompetencymatrix.www.dto.InventoryDTO["audit"])

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)

据我了解,mockito 应该模拟 Service 类,并且测试不会进入其中...... 据我所知,Auditor 对 Controller 类没有任何影响。

【问题讨论】:

    标签: java spring unit-testing controller mockito


    【解决方案1】:

    错误说明了一切:

    无法构造实例 com.teamcompetencymatrix.www.dto.AuditDTO(没有创作者,默认 构造函数,存在)

    请求体无法转化为DTO,尝试在AuditDTO添加一个空的构造函数和setter

    【讨论】:

    • 但它为什么还要交给 DTO?该服务适用于 DTO,但被嘲笑。所以它不应该进入类,它应该在调用inventoryService.add方法时从列表中返回inventoryList.get(0)...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多