美文网首页
JUnit的@RunWith注解是怎么运行的?

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

作者: 抬头挺胸才算活着 | 来源:发表于2021-11-03 21:43 被阅读0次

参考资料:
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默认的注解

相关文章

  • SpringBoot集成test测试

    @runWith注解作用:--@RunWith就是一个运行器--@RunWith(JUnit4.class)就是指...

  • Junit

    1. Junit注解 1.1 类注解 @RunWith : 使用指定的类运行测试类 1.2 方法注解 @Test ...

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

    参考资料:JUnit - Understanding how @RunWith works[https://www...

  • Spring中使用@RunWith整合的测试注解

    例如: @RunWith就是一个运行器 @RunWith(JUnit4.class)就是指用JUnit4来运行 @...

  • 测试用例

    测试用例 @RunWith 运行器,Spring中通常用于对JUnit的支持 @RunWith(SpringJUn...

  • Java – 理解 @ExtendWith(SpringExte

    在JUnit5之前,我们用@RunWith(MockitoJUnitRunner.class)注解,使用Mocki...

  • spring-boot+junit 参数化测试

    1、junit 参数测试四个步骤 a、对测试类添加注解 @RunWith(Parameterized.class)...

  • Spring中的测试

    我们先从最基础的spring项目说起1.首先是依赖 2.测试类 @RunWith :是Junit的注解,它会提供一...

  • @Runwith

    概念 testRunner : 运行测试类的类 @Runwith : 告诉junit的框架应该是使用哪个testR...

  • 4 注解

    1、Annotation(注解) 概述注解起到标识做用。比如Junit的@Test注解。Junit会在运行时检查方...

网友评论

      本文标题:JUnit的@RunWith注解是怎么运行的?

      本文链接:https://www.haomeiwen.com/subject/wefczltx.html