PowerMockoito中@PrepareForTest作用
源码注释:
/**
* This annotation tells PowerMock to prepare certain classes for testing.
* Classes needed to be defined using this annotation are typically those that
* needs to be byte-code manipulated. This includes final classes, classes with
* final, private, static or native methods that should be mocked and also
* classes that should be return a mock object upon instantiation.
* <p>
* This annotation can be placed at both test classes and individual test
* methods. If placed on a class all test methods in this test class will be
* handled by PowerMock (to allow for testability). To override this behavior
* for a single method just place a {@code @PrepareForTest} annotation
* on the specific test method. This is useful in situations where for example
* you'd like to modify class X in test method A but in test method B you want X
* to be left intact. In situations like this you place a
* {@code @PrepareForTest} on method B and exclude class X from the
* {@link #value()} list.
* <p>
可以看出 对于 静态方法,私有方法, final 方法,在用powermock做单元测试的时候,需要增加注解@PrepareForTest,
这个注解的作用就是:该注释告诉PowerMock(ito)列出的类将需要在字节码级别上进行操作。
例如, 类 A 有一个静态方法 funa(),这方法在类B中的非静态 funb()中使用,
那么我们在对funb()做测试的测试时候,就需要在单元测试类中增加@PrepareForTest(A.class)
按照我调试的结果,最后进入实现类 PrepareForTestExtractorImpl中,把类A的全部限定名称获取到并传递到待mock的列表中,执行方法具体是:
大致是获取有此注解的类的全限定名称加入到待mock的类列表中,自动模拟一个新对象。
如有错误之处,敬请指正,声明下笔者也还未彻底搞清楚这块,也欢迎大神指点。
引用: