1

我的问题是模拟和测试一个实例化其他类并调用它们的方法的方法。为了项目的安全,我就不赘述了。要测试的方法是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
       }

    }

}
4

1 回答 1

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) 然后模拟上面的方法。

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

于 2013-06-05T23:29:11.193 回答