Mockito - 在目标类方法中验证另一个对象的方法调用

时间:2018-04-21 20:27:43

标签: java unit-testing junit mockito

我正在为涉及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一次?

2 个答案:

答案 0 :(得分:1)

由于在测试方法中正在创建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());

参考Class ArgumentCaptor<T>

答案 1 :(得分:1)

将cookie创建移动到新方法:

     } else {
            Cookie c = createNewCookie("favourites", propId);
            c.setMaxAge(60 * 60 * 24 * 365 * 5);
...
...
...

protected Cookie createNewCookie(String name, String id){
    return new Cookie(name, id);
}

然后在单元测试中验证是否调用了此方法:

@Mock
HttpServletRequest request;

@Mock
HttpServletResponse response;

@BeforeTest
public void init() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testAddPropertyToUserWishlist() throws IOException {

    WishlistController testedObject = Mockito.spy(new WishlistController());

    Boolean outcome = testedObject.addPropertyToUserWishlist(request, response, "propid");

    Mockito.verify(testedObject).createNewCookie("favourites","propid");
}

如果要测试对新cookie执行的操作,可以覆盖此方法并以这种方式将自己的cookie实例注入测试类:

@Mock
Cookie myNewCookie;

@Test
public void testAddPropertyToUserWishlist() throws IOException {

    WishlistController testedObject = Mockito.spy(new WishlistController(){
        @Override
        protected Cookie createNewCookie(String id, String name){
            return myNewCookie;
        }
    });

    Boolean outcone = testedObject.addPropertyToUserWishlist(request, response, "propid");

    Mockito.verify(testedObject).createNewCookie("favourites","propid");
    Mockito.verify(myNewCookie, Mockito.times(1)).setMaxAge(60 * 60 * 24 * 365 * 5);
}