我是春天和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);
}
我的模拟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());
}
有人可以帮助我吗?
答案 0 :(得分: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.从你的servlet-context.xml中分离你的客户端“real”,这样就不会在测试中加载它。
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。