代码之家  ›  专栏  ›  技术社区  ›  katiex7

如何使用mockmvc作为请求体传递对象?

  •  0
  • katiex7  · 技术社区  · 7 年前

    下面是我在代码中解释的场景和问题

    // the call that I am making in my test, please note that myService is a Mocked object
    Foo foo = new Foo();
    when(myService.postFoo(foo)).thenReturn(true); 
    mockMvc.perform(post("/myEndpoint")
        .contentType(APPLICATION_JSON_UTF8)
        .content(toJsonString(foo))
        .andExpect(status().isAccepted());
    
    
    // this is the controller method that get's called
    @PostMapping("/myEndpoint") 
    @ResponseStatus(code = HttpStatus.ACCEPTED) 
    public String postFoo(@RequestBody Foo foo) { 
        if (myService.postFoo(foo)) {
             return "YAY"; 
        } 
        return "" + 0 / 0; 
    }
    

    我面临的问题是mockmvc的post传入的foo是foo的一个新实例,因此myservice.postfoo(foo)的if语句失败。我假设引擎使用我的foo对象的jsonstring创建了一个新的字段完全相同的对象,而不是一个不同的对象,从而使“if”语句失败。

    我该怎么解决这个问题?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Master Slave    7 年前