JUnit的@RunWith注解是怎么运行的?

2021-11-03  本文已影响0人  抬头挺胸才算活着

参考资料:
JUnit - Understanding how @RunWith works

在使用PowerMock的时候我们需要给测试的类添加@RunWith(PowerMockRunner.class)注解,接下来让我们了解下@RunWith的原理。

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

  }
}

ParentRunner:有层次地调用test
BlockJUnit4Runner:就是JUnit默认的注解

上一篇 下一篇

猜你喜欢

热点阅读