如何为此Rest客户端控制器编写正确的Junit测试

时间:2016-07-29 13:25:13

标签: java spring unit-testing junit

我知道这是一个非常大胆的问题,但也许某人至少可以以正确的方式领导......

控制器:

@RequestMapping(value="/users", method=RequestMethod.GET)
    public String listUsers(Model model) {  
        model.addAttribute("logedUser", logedUser);
        final String uri = new String(URL + "list");
        RestTemplate restTemplate = new RestTemplate();     
        HttpEntity entity = getHeader();
        HttpEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);         
        String temp = response.getBody();
        ObjectMapper mapper = new ObjectMapper();
        try {       
            User[] obj = mapper.readValue(temp, User[].class);
            List<User> userList= Arrays.asList(obj);
            model.addAttribute("users", userList);
            //String temps = logedUser.getUserType().toString();
            System.out.println(logedUser.getUserType().toString());

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {          
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }               
        return "users";
    }

测试: @Test

public void btestList() throws Exception{

    List<User> users = new ArrayList<>();

    users.add(new User());
    users.add(new User());
    UserController mock = org.mockito.Mockito.mock(UserController.class);
    Mockito.when(mock.listUsers(model)).thenReturn((String) "users");

    mockMvc.perform(get("/users"))
        .andExpect(status().isOk())
        .andExpect(view().name("users"));

}

所以,试着为这个控制器写一个测试并得到了这个: org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.springframework.web.client.HttpClientErrorException:400 Bad Request     在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)     在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:621)

我在这里做错了什么? P.s控制器工作正常。

1 个答案:

答案 0 :(得分:0)

使用Mockito.when(mock.listUsers(model)).thenReturn((String) "users");,您实际上是在嘲笑您要测试的方法。

此外,使用@RestController时,返回值不是视图,因此我不确定view().name("users")是否正确。也许它可能有用,但重点是RestController并不意味着返回视图。此外,您的代码并未显示您如何创建mockMvc,因此我不确定它是如何连接的。

以下测试代码可行:

public class UserControllerTest {
    @InjectMocks
    private UserController userController;

    private MockMvc mockMvc;

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

    @Test
    public void btestList() throws Exception {
        mockMvc.perform(get("/users"))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("users"));
    }
}

控制器的简化版本:

@RestController
public class UserController {
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String listUsers(Model model) {
        return "users";
    }
}