参考资料:
JUnit - Understanding how @RunWith works
在使用PowerMock的时候我们需要给测试的类添加@RunWith(PowerMockRunner.class)
注解,接下来让我们了解下@RunWith的原理。
- @RunWith注解原理
@Runwith给指定了JUnit测试的时候使用的Runner类。
我们看下下面一个自定义的Runner类的例子,它的构造函数由JUnit输入了一个要测试的类,Runner在run方法中通过反射依次跑每个测试带有@Test注解的方法,run方法的输入参数RunNotifier用来给JUnit发送消息,
public class MyRunner extends Runner {
private Class testClass;
public MyRunner(Class testClass) {
this.testClass = testClass;
}
@Override
public Description getDescription() {
return Description.createTestDescription(testClass, "My runner description");
}
@Override
public void run(RunNotifier notifier) {
System.out.println("running the tests from MyRunner. " + testClass);
try {
Object testObject = testClass.newInstance();
for (Method method : testClass.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
notifier.fireTestStarted(Description.EMPTY);
method.invoke(testObject);
notifier.fireTestFinished(Description.EMPTY);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
-
其他Runner类
Runner类继承层级
ParentRunner:有层次地调用test
BlockJUnit4Runner:就是JUnit默认的注解
网友评论