Mockito Argument Captor Test返回整个JSON对象

时间:2015-10-13 19:46:35

标签: spring-mvc mockito

我有一个Mockito测试,它使用Argument Captor验证新用户是否正确发布:

@Test
public void testPostUser() throws Exception{
   User user = new User(1L, "tonkatruck");

   when(userService.addUser(any(User.class))).thenReturn(user);

   mockMvc.perform(post("/api/user")
        .content("{\"userId\":\"1\",\"userName\":\"tonkatruck\"}")
        .contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.userName", is(user.getUserName())))
            .andExpect(status().isCreated())
            .andDo(print());


   //verify(userService).addUser(any(User.class));
   verify(userService).addUser(userCaptor.capture());

   //get the username from what was captured in the POST method and assert that it posted the correct username
   String username = userCaptor.getValue().getUserName();
   assertEquals("tonkatruck", username);
}

测试失败,错误为:

Failed tests:   testPostUser(com.ucrisko.libroomreserve.tests.UserControllerTest): expected:<[tonkatruck]> but was:<[{"userId":"1","userName":"tonkatruck"}]>

我在userCaptor对象上调用User类的getUserName()方法,所以任何想法为什么断言都是整个JSON User对象?

1 个答案:

答案 0 :(得分:1)

要重现您的错误,我已经尝试过您的测试。已经做了一些假设来实现控制器和服务。请查找班级测试的更新:

package mvc;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import javax.ws.rs.core.MediaType;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

public class UserTest {

    @InjectMocks
    private UserController userController;

    @Mock
    private UserService userService;

    @Captor
    private ArgumentCaptor<User> userCaptor;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    }

    @Test
    public void testPostUser() throws Exception {

        User user = new User(1L, "tonkatruck");

        when(userService.addUser(any(User.class))).thenReturn(user);

        mockMvc.perform(post("/api/user") //
                .contentType(MediaType.APPLICATION_JSON) //
                .content("{\"userId\":\"1\",\"userName\":\"tonkatruck\"}")) //
                .andExpect(jsonPath("$.userName", is(user.getUserName()))) //
                .andExpect(status().isOk()).andDo(print());

        Mockito.verify(userService).addUser(userCaptor.capture());

        assertEquals("tonkatruck", userCaptor.getValue().getUserName());
    }
}

用于测试的Maven依赖项:

<dependencies>

        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>spring-mock-mvc</artifactId>
            <version>2.6.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>

</dependencies>

结果:确定

enter image description here