无法使用mockito模拟webservice客户端

时间:2016-08-05 06:25:40

标签: spring-mvc junit mocking mockito spring-test

我正在测试一个spring mvc控制器,它可以自动连接一个web服务客户端,并且它被模拟为vai mockito。但嘲笑不起作用。调用“verify(stuClient,times(1))。getAllStudents(sAndPCommand);”在测试中返回

Wanted but not invoked:

stuClient.getAllStudents(
    com.xyz.crudserviceclient.utilitybeans.SortablePagedCommand@3028e50e
);
-> at com.xyz.controllers.StudentControllerTest.testGetHomePage(StudentControllerTest.java:101)
Actually, there were zero interactions with this mock.

    at com.xyz.controllers.StudentControllerTest.testGetHomePage(StudentControllerTest.java:101).....

以下是我在测试中的控制器方法:

@RequestMapping(value = "/getHomePage.do", method = RequestMethod.GET)
  public ModelAndView getHomePage(@RequestParam(value = "first", required = false) Integer first,
      @RequestParam(value = "max", required = false) Integer max, @RequestParam(value = "sortBy",
      required = false) String sortBy,
      @RequestParam(value = "sortDirection", required = false) String sortDir) {

    ModelAndView mav = new ModelAndView("home");

    SortablePagedCommand sortablePagedCommand = new SortablePagedCommand();
    sortablePagedCommand.setFirst(first);
    sortablePagedCommand.setMax(max);
    sortablePagedCommand.setSort(sortBy);
    sortablePagedCommand.setSortDir(sortDir);

    PagedResult<StudentBean> students = studentServiceClient.getAllStudents(sortablePagedCommand);
    List<StudentBean> studentList = students.getItems();

    int noOfRecords = students.getUnfilteredItems();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / max);

    mav.addObject("sortByField", sortBy);
    mav.addObject("sortDirField", sortDir);
    mav.addObject("studentList", studentList);
    mav.addObject("noOfPages", noOfPages);
    mav.addObject("currentPage", first);

    return mav;
  }

以下是我的测试类:

package com.xyz.controllers;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import java.sql.Date;
import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.xyz.crudserviceclient.beans.StudentBean;
import com.xyz.crudserviceclient.client.StudentServiceClient;
import com.xyz.crudserviceclient.utilitybeans.PagedResult;
import com.xyz.crudserviceclient.utilitybeans.SortablePagedCommand;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/dispatcher-servlet.xml" })
@WebAppConfiguration
public class StudentControllerTest {
    private MockMvc mockMvc;
    @InjectMocks
    private StudentController controller;
    @Mock
    private StudentServiceClient stuClient;
    @Autowired
    private WebApplicationContext webAppContext;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
        Mockito.reset(stuClient);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testGetHomePage() throws Exception {
        StudentBean sb1 = new StudentBean();
        sb1.setFirstName("Sai");
        sb1.setLastName("Palaparthi");
        sb1.setGender("Male");
        sb1.setDOB(new Date(System.currentTimeMillis()));
        sb1.setEmail("v.p@gmail.com");
        sb1.setMobileNumber("8121157247");
        sb1.setAddress("Huda");
        sb1.setCourses(Arrays.asList("Math", "Chem"));

        StudentBean sb2 = new StudentBean();
        sb2.setFirstName("Viswanath");
        sb2.setLastName("Palaparthi");
        sb2.setGender("Male");
        sb2.setDOB(new Date(System.currentTimeMillis()));
        sb2.setEmail("v.p@gmail.com");
        sb2.setMobileNumber("8121157248");
        sb2.setAddress("Huda");
        sb2.setCourses(Arrays.asList("Math"));

        PagedResult<StudentBean> pResult = new PagedResult<StudentBean>(
                Arrays.asList(sb1, sb2), 2);
        pResult.setFirst(0);
        pResult.setUnfilteredItems(2);

        Integer first = 0;
        Integer max = 5;
        String sortBy = "firstname";
        String sortDir = "asc";

        SortablePagedCommand sAndPCommand = new SortablePagedCommand();
        sAndPCommand.setFirst(first);
        sAndPCommand.setMax(max);
        sAndPCommand.setSort(sortBy);
        sAndPCommand.setSortDir(sortDir);
        Mockito.when(stuClient.getAllStudents(sAndPCommand))
                .thenReturn(pResult);

        mockMvc.perform(
                get("/getHomePage.do").param("first", String.valueOf(first))
                        .param("max", String.valueOf(max))
                        .param("sortBy", sortBy)
                        .param("sortDirection", sortDir))
                .andExpect(status().isOk())
                .andExpect(view().name("home"))
                .andExpect(forwardedUrl("/jsps/home.jsp"))
                .andExpect(model().attribute("sortByField", is(sortBy)))
                .andExpect(model().attribute("sortDirField", is(sortDir)))
                .andExpect(model().attribute("noOfPages", 1))
                .andExpect(model().attribute("currentPage", is(first)))
                .andExpect(model().attribute("studentList", hasSize(2)))
                .andExpect(
                        model().attribute(
                                "studentList",
                                hasItem(allOf(
                                        hasProperty("firstName", is("Sai")),
                                        hasProperty("lastName",
                                                is("Palaparthi")),
                                        hasProperty("gender", is("Male")),
                                        hasProperty(
                                                "dob",
                                                is(new Date(System
                                                        .currentTimeMillis()))),
                                        hasProperty("email",
                                                is("v.p@gmail.com")),
                                        hasProperty("mobileNumber",
                                                is("8121157247")),
                                        hasProperty("address", is("Huda")),
                                        hasProperty("courses",
                                                hasItems("Math", "Chem"))))))
                .andExpect(
                        model().attribute(
                                "studentList",
                                hasItem(allOf(
                                        hasProperty("firstName",
                                                is("Viswanath")),
                                        hasProperty("lastName",
                                                is("Palaparthi")),
                                        hasProperty("gender", is("Male")),
                                        hasProperty(
                                                "dob",
                                                is(new Date(System
                                                        .currentTimeMillis()))),
                                        hasProperty("email",
                                                is("v.p@gmail.com")),
                                        hasProperty("mobileNumber",
                                                is("8121157248")),
                                        hasProperty("address", is("Huda")),
                                        hasProperty("courses", hasItems("Math"))))));

        verify(stuClient, times(1)).getAllStudents(sAndPCommand);
        verifyNoMoreInteractions(stuClient);

    }
}

1 个答案:

答案 0 :(得分:0)

你做错了 - 这显然是一个整合测试,所以为什么要涉及Mockito呢?另外,你将mocks注入到控制器字段中,但你的测试没有调用控制器字段 - 它们正在与Spring上下文中的控制器bean进行交互。

查看this excellent tutorial,尤其是单元测试部分。

总结一下,您的测试设置需要更改,您不需要任何注释,而且您必须为控制器使用独立的MockMvc设置:

public class StudentControllerTest {
    private MockMvc mockMvc;

    @InjectMocks
    private StudentController controller;

    @Mock
    private StudentServiceClient stuClient;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        Mockito.reset(stuClient);
    }