Jmockit对接口与基类的mock
对一个类或接口使用@Capturing,那么该类的所有子类或接口所有实现都将处于mocked状态,即使是临时定义的实现或子类也会是mocked状态
接口示例:
//接口
public interface JInterface
{
public String methodA(String para);
}
//实现
public class ImplA implements JInterface
{
public String methodA(String para)
{
return "oringinal methodA " + para;
}
}
Mock测试
@Test
public void test1(@Capturing final JInterface jInterface)//JInterface接口被mocked
{
JInterface i = new ImplA();
System.out.println(i.methodA("d"));//null 因为被mocked
new NonStrictExpectations()
{
{
jInterface.methodA(anyString);
returns("first mocked impl method", "second mocked impl method");//
}
};
System.out.println(i.methodA("ohad")); //record的第一个结果first mocked impl method
//新定义的实现也将处于mocked状态
JInterface i3 = new JInterface()
{
public String methodA(String para)
{
// TODO Auto-generated method stub
return null;
}
};
System.out.println(i3.methodA("dpfiojaoifh")); //record的第二个结果second mocked impl method
}
继承示例:
//父类
public abstract class Base
{
abstract public String methodA();
}
//子类
public class ExtendA extends Base
{
@Override
public String methodA()
{
return "original method";
}
Mock测试
@Test
public void test4(@Capturing final Base base)
{
Base obj = new ExtendA();
System.out.println(obj.methodA());//null
new NonStrictExpectations()
{
{
base.methodA();
//这里相当于returns(Object firstValue, Object... remainingValues)
result = "mocked method1";
result = "mocked method2";
}
};
System.out.println(obj.methodA());//mocked method1
Base obj1 = new Base()
{
@Override
public String methodA()
{
return null;
}
};
System.out.println(obj1.methodA());//mocked method2
}
本文介绍如何使用JMockit对Java接口及其实现类、基类及其子类进行Mock操作。通过示例展示了如何对指定接口或基类进行Mock,以及如何为这些Mock对象设置预期行为。
2087

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



