使用PowerMock模拟具有返回值的方法链

时间:2013-06-05 10:28:49

标签: testing mocking testng easymock powermock

我想模拟以下代码:

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

返回伪造号码。我如何使用PowerMock& EasyMock \ Mockito?

1 个答案:

答案 0 :(得分: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  
    }
}

如果它可以帮助你,请投票给我