0

我是spring和junit的新手。我想使用 mockito 测试我的控制器。我使用 mock-mvc 编写了测试用例,但我的一位资深人士告诉我尝试使用 mockito。我在谷歌搜索它我不知道模拟单元测试。

@Autowired
private Client client;

 @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String initUserSearchForm(ModelMap modelMap) {
        User user = new User();
        modelMap.addAttribute("User", user);
        return "user";
    }

    @RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(HttpServletRequest request,@ModelAttribute("userClientObject") UserClient userClient) {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        return client.getUserByName(userClient, firstName, lastName);
    }

我的 mock-mvc 测试用例是

@Test
    public void testInitUserSearchForm() throws Exception {
        this.liClient = client.createUserClient();
        mockMvc.perform(get("/user"))
                .andExpect(status().isOk())
                .andExpect(view().name("user"))
                .andExpect(forwardedUrl("/WEB-INF/pages/user.jsp"));
    }

    @Test
    public void testGeUserByName() throws Exception {
        String firstName = "Wills";
        String lastName = "Smith";         
        mockMvc.perform(get("/user-byName"))
                .andExpect(status().isOk());

    }

有人可以帮我吗?

4

1 回答 1

1

1.在xml中定义这个客户端mockito,我们称之为client-mock.xml

<bean id="client" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="your org.Client" /> //interface name
</bean>

如果 Client 不是接口,您可能必须将 cglib 添加到您的类路径中。

2.将您的客户端“真实”与 your-servlet-context.xml 分开,这样它就不会在测试中加载。

import static org.mockito.Mockito.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:your-servlet-context.xml",
    "classpath:client-mock.xml" })
@WebAppConfiguration
public class YourTests {

    @Autowired
    private Client client;

    @Test
    public void testGeUserByName() throws Exception {
        String firstName = "Wills";
        String lastName = "Smith";         
        String returning = //JSON I presume 

        UserClient userClientObject = ;//init

        when(client).getUserByName(userClientObject, firstName, lastName)
        .thenReturn(returning);//define stub call expectation


        mockMvc.perform(get("/user-byName").sessionAttr("userClientObject", userClientObject))
            .andExpect(status().isOk());

    }

}

顺便说一句,如果在测试中使用“真实”客户端不是非常复杂或昂贵,那么是否使用 mockito 并不重要。

你可以在这里获得Mockito Doc

于 2013-07-29T04:49:07.933 回答