关键词:Verifications 想验证被Mock的类的某个方法是否被调用
单元测试类清单
有时候我们想验证某个类的方法是否被正确调用的时候,上述Verifications就派上用场了
/**
* 演示验证被Mock的类的某个方法是否被调用
* @sina weibo regbin@tom.com
*/
public class ServiceTest {
@Mocked
Remote remote;
@Test
public void testDoFuncYes() {
Service service = new Service();
service.doFunc(true, 1);
new Verifications() {
{
remote.doSomething(anyInt);//表示这个方法会被执行
//remote.doSomething(1);//表示这个方法会被执行,而且参数是1;在当前case,会通过
//remote.doSomething(2);//表示这个方法会被执行,而且参数是2;在当前case,这个会不被通过
}
};
}
@Test
public void testDoFuncNo() {
Service service = new Service();
service.doFunc(false, 1);
new Verifications() {
{
remote.doSomething(anyInt);
times = 0;//调用次数,0表示上面方法不会被调用
}
};
}
private static class Remote {
public void doSomething(int a) {
}
}
private static class Service {
private Remote remote = new Remote();
public void doFunc(boolean flag, int a) {
if (flag) {
remote.doSomething(a);
}
}
}
}
小结
有时候我们想验证某个类的方法是否被正确调用的时候,上述Verifications就派上用场了

本文展示了如何使用Verifications来验证被Mock的类的某个方法是否被正确调用,包括测试用例的实现与解析。
1965

被折叠的 条评论
为什么被折叠?



