Mockito通过Mock对象,替换原先依赖的真实对象,就可以避免外部的影响,得到更准确的结果。
1、验证方法调用。
@Test
public void testLogin() {
UserManager mockUserManager = Mockito.mock(UserManager.class);
LoginPresenter loginPresenter = new LoginPresenter();
loginPresenter.setUserManager(mockUserManager);
loginPresenter.login("xiaochuang", "xiaochuang password");
//Mockito.verify(objectToVerify).methodToVerify(arguments)
Mockito.verify(mockUserManager).performLogin(anyString(), anyString());
}
2、指定mock对象的某个方法返回特定的值。
@Test
@JSpec(desc = "should mock return given value")
public void test() {
PasswordValidator validator = Mockito.mock(PasswordValidator.class);
Mockito.when(validator.verifyPassword("xiaochuangishandsome")).thenReturn(true);
Assert.assertEquals(true, validator.verifyPassword("xiaochuangishandsome"));
Mockito.when(validator.verifyPassword(anyString())).thenReturn(true);
Assert.assertEquals(true, validator.verifyPassword("xiaochuangishandsome11"));
}
3、指定mock对象执行特定的动作
@Test
@JSpec(desc = "should mock perform certain action")
public void testMockAnswer() {
UserManager mockUserManager = Mockito.mock(UserManager.class);
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
//这里可以获得传给performLogin的参数
Object[] arguments = invocation.getArguments();
NetworkCallback callback = (NetworkCallback) arguments[2];
callback.onFailure(500, "Server error");
return 500; //对于如果mock的是非void方法来说,这个将作为目标方法的返回值
}
}).when(mockUserManager).performLogin(anyString(), anyString(), any(NetworkCallback.class));
mockUserManager.performLogin("xiaochuang", "xiaochuang password", Mockito.mock(NetworkCallback.class));
}
4、验证实际方法调用的功能
@Test
public void testSpy() {
//跟创建mock类似,只不过调用的是spy方法,而不是mock方法。spy的用法
PasswordValidator spyValidator = Mockito.spy(PasswordValidator.class);
//在默认情况下,spy对象会调用这个类的real implementation,并返回相应的返回值
boolean result = spyValidator.verifyPassword("xiaochuang_is_handsome");//true
Assert.assertTrue(result);
result = spyValidator.verifyPassword("xiaochuang_is_not_handsome"); //false
Assert.assertFalse(result);
//也可以指定spy对象的方法的行为
Mockito.when(spyValidator.verifyPassword(anyString())).thenReturn(true);
result = spyValidator.verifyPassword("xiaochuang_is_not_handsome");
Assert.assertTrue(result);
Mockito.verify(spyValidator, Mockito.times(2)).verifyPassword("xiaochuang_is_not_handsome");
}