【问题标题】:Powermock testing a static method with other methods of other class in it to return nullPowermock 使用其中其他类的其他方法测试静态方法以返回 null
【发布时间】:2013-06-01 04:46:28
【问题描述】:

我的问题是模拟和测试一个实例化其他类并调用它们的方法的方法。为了项目的安全,我就不赘述了。要测试的方法是A的launch()方法。测试规范想让b.methodOfB返回null。另一个测试规范是 c.getinput() 方法返回 null

public class A{

    public static void launch()
    {
       //instantiation of other classes that will be used
       B b = new B();
       C c = new C();

       //class C has a method that gets user information from the console and returns a string
       //i would like to mock c.getinput() to return null
       while (c.getinput().compareToIgnoreCase("q") != 0) {
           //would also like to mock the b.methodOfB() to return null for testing im having a hard time doing this
           b.methodOfB();//returns something not null
       }

    }

}

【问题讨论】:

    标签: java junit4 easymock powermock


    【解决方案1】:

    这是使用 PowerMockito 的单元测试代码。

    @Runwith(PowerMockRunner.class)
    public void class ATest
    {
    
      public void testLaunch()
      {
         B b = PowerMockito.mock(B.class);
         C c = PowerMockito.mock(C.class);
         PowerMockito.when(c.getInput()).thenReturn(null);
         PowerMockito.when(b.methodOfB()).thenReturn(null);
         // now call your methods 
       }
    
     }
    

    如果你必须在一个类中模拟静态方法,你必须使用 mockStatic(Classname.class) 然后模拟上面的方法。

    注意:我没有编译这段代码。我刚刚输入了回复。如果你喜欢投票:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      相关资源
      最近更新 更多