在抽象类中模拟静态方法

时间:2017-05-15 06:56:28

标签: java junit mockito powermock

我有一个类A,它调用抽象类B的静态方法,抛出一些异常。我想测试这个例外。我正在使用junit 4.1,mockito 1.9.5和powermock 1.6.6。课程是:

 abstract class B {
 public static void meth(String str) throws SomeException1, SomeException2,SomeException3 {
 //some code 
  }
}

class A{
 public void method() throws SomeException1, SomeException2,SomeException3 {
  B.meth1("abc");
  }
}

我想测试这些异常,这是我的测试类

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(B.class)
class Test throws Throwable {

public void testException(){
PowerMockito.mockStatic(B.class); //Line 6
when(B.meth(Mockito.any(String.class))).thenThrow(new SomeException1(), new SomeException2(), new SomeException3() );
A obj=new A();
obj.method();
   }
  }
}

执行此测试用例时,我得到一个异常

org.powermock.api.mockito.ClassNotPreparedException: 
The class B not prepared for test.
To prepare this class, add class to the '@PrepareForTest' annotation.
In case if you don't use this annotation, add the annotation on class or  method level. 

at org.powermock.api.mockito.expectation.reporter.MockitoPowerMockReporter.classNotPrepared(MockitoPowerMockReporter.java:32)
at org.powermock.api.mockito.internal.mockcreation.MockTypeValidatorFactory$DefaultMockTypeValidator.validate(MockTypeValidatorFactory.java:38)
at org.powermock.api.mockito.internal.mockcreation.AbstractMockCreator.validateType(AbstractMockCreator.java:10)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:56)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:71)
at Test.testException(Test.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

关于我为什么会这样做的任何建议?

2 个答案:

答案 0 :(得分:2)

您需要:@RunWith(PowerMockRunner.class)

答案 1 :(得分:1)

您可以使用powermock来模拟静态方法。

代码示例

@RunWith(PowerMockRunner.class)
public class TestStaticMethodExample {
    private SomeClass c = new SomeClass ("g", "123");

    @PrepareForTest({ SomeStatic.class })
    @Test
    public void stubStaticMethod() {

        PowerMockito.mockStatic(SomeStatic.class);

        PowerMockito.when(SomeStatic.getSummary()).thenReturn(new 
    SomeClass("t", 9999));

    }

}