简体   繁体   English

在抽象类中模拟静态方法

[英]Mocking a static method in abstract class

I have a class A which calls a static method of an abstract class B which throws some exception. 我有一个类A,它调用抽象类B的静态方法,它抛出一些异常。 I wanted to test for this exception. 我想测试这个例外。 I am using junit 4.1, mockito 1.9.5 and powermock 1.6.6. 我正在使用junit 4.1,mockito 1.9.5和powermock 1.6.6。 The classes are : 课程是:

 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");
  }
}

I want to test these exceptions and here is my test class 我想测试这些异常,这是我的测试类

@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();
   }
  }
}

While executing this test case I get an exception 在执行此测试用例时,我得到一个例外

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)

Any suggestion as to why am I getting this ? 有关为什么我得到这个的任何建议?

你需要这个: @RunWith(PowerMockRunner.class)

You can use powermock to mock static method. 您可以使用powermock来模拟静态方法。

Code example 代码示例

@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));

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM