我想模拟下面的代码:
int num = MySingelton.getInstance().getA().getB().getC();
返回假数字。我如何使用PowerMock &EasyMock 5 ?
是的,这是可能的。我已经用powermockit为你创建了一个示例代码。
创建一个单例类…
public class SingletonClassUtil
{
private static SingletonClassUtil singletonClassUtil;
private SingletonClassUtil(){}
private String name;
public static SingletonClassUtil getInstance()
{
if(singletonClassUtil!=null)
{
singletonClassUtil = new SingletonClassUtil();
}
return singletonClassUtil;
}
public String getA()
{
return name;
}
}
现在使用PowerMock测试这个类。
public class SingletonTest
{
public void testSingleton() throws Exception
{
PowerMockito.suppress(PowerMockito.constructor(SingletonClassUtil.class));
PowerMockito.mockStatic(SingletonClassUtil.class);
SingletonClassUtil singletonClassUtil = PowerMockito.mock(SingletonClassUtil.class);
PowerMockito.when(singletonClassUtil.getA()).thenReturn("A");
System.out.print(singletonClassUtil.getA());
// add your code here to access inner class methods
}
}
如果对你有帮助就投我一票