Powermock使用其他类的其他方法测试静态方法以返回null

时间:2013-06-01 04:46:29

标签: java junit4 easymock powermock

我的问题是模拟和测试实例化其他类并调用其方法的方法。对于项目安全,我不会详细介绍。要测试的方法是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
       }

    }

}

1 个答案:

答案 0 :(得分:0)

以下是使用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),然后模拟上述方法。

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