问题
I am new to spring and junit. I want to test my controllerusing mockito.I wrote test case using mock-mvc but one of my senior told try with mockito. I searched it in google i have no idea about mockito unit testing.
@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);
    }
My mock-mvc test case is
@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());
    }
Could anyone help me?
回答1:
1.Define this client mockito in an xml, let's call it client-mock.xml
<bean id="client" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="your org.Client" /> //interface name
</bean>
You might have to add cglib to your classpath if Client is not an interface.
2.Seperate your client "real" from your-servlet-context.xml, so it would not be loaded in tests.
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());
    }
}
By the way, it doesn't matter whether you use mockito or not if it's not very complex or expensive to use "real" Client in tests.
You can get Mockito Doc here.
来源:https://stackoverflow.com/questions/17915828/how-to-write-mockito-test-case