2

我想模拟以下代码:

int num = MySingelton.getInstance().getA().getB().getC();

返回一个伪造的号码。我如何使用 PowerMock 和 EasyMock\Mockito 来做到这一点?

4

1 回答 1

1

是的,它可能。我使用 PowerMockito 为您创建了一个示例代码。

创建一个单例类..

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  
    }
}

如果对你有帮助,请投票给我

于 2013-06-05T22:08:58.267 回答