我正在为涉及 cookie 的方法编写单元测试。方法如下。
public Boolean addPropertyToUserWishlist(HttpServletRequest request,
HttpServletResponse response, String propId) throws IOException {
String message = "";
try {
Cookie[] cookies = request.getCookies();
if (checkCookieValueExists(cookies, propId)) {
message = "Already added to favourites!";
} else {
if (checkCookieExists(cookies)) {
for (Cookie cookie : cookies) {
if ("favourites".equals(cookie.getName())) {
cookie.setValue(cookie.getValue() + "_" + propId);
cookie.setMaxAge(60 * 60 * 24 * 365 * 5);
response.addCookie(cookie);
message = "Added to Favourites!";
break;
}
}
} else {
Cookie c = new Cookie("favourites", propId);
c.setMaxAge(60 * 60 * 24 * 365 * 5);
response.addCookie(c);
message = "Added to Favourites!";
}
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
这是该方法的单元测试。
@Test
public void testAddPropertyToUserWishlist() throws Exception {
System.out.println("addPropertyToUserWishlist");
//decleration
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
Cookie c = mock(Cookie.class);
Cookie[] cookies = new Cookie[2];
String propId = "5"; //testing the for property with id 5
WishlistController instance = Mockito.spy(new WishlistController());
// training
Mockito.doReturn(false).when(instance).checkCookieExists(cookies);
Mockito.doReturn(false).when(instance).checkCookieValueExists(cookies, propId);
when(request.getCookies()).thenReturn(cookies);
// testing
Boolean result = instance.addPropertyToUserWishlist(request, response, propId);
//verify(response, times(1)).addCookie(c);
assertTrue(result);
}
我想测试 cookie 是否已创建。因为我没有在浏览器中执行这段代码。那么我如何验证是否调用了用于创建新 cookie 的构造函数以及是否调用了方法 setMaxAge
一次?
最佳答案
自 Cookie
在被测试的方法中创建时,您实际上没有任何方法可以控制其行为,因此也没有理由模拟它。
相反verify
如果response.addCookie
被调用并捕获作为参数传入的 cookie。
从那里,断言其值(如果已知)。
//Arrange
//...code removed for brevity
// Act
Boolean result = instance.addPropertyToUserWishlist(request, response, propId);
//Assert
ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class);
//Same as verify(response, times(1)) and captures the passed argument
verify(response).addCookie(cookieCaptor.capture());
Cookie cookie = cookieCaptor.getValue();
int expectedAge = 60 * 60 * 24 * 365 * 5;
String expectedName = "favourites";
assertEquals(expectedAge, cookie.getMaxAge());
assertEquals(expectedName, cookie.getName());
assertEquals(propId, cookie.getValue());
关于java - Mockito - 验证目标类方法内另一个对象的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49959953/