@Runwith

概念

testRunner : 运行测试类的类

@Runwith : 告诉junit的框架应该是使用哪个testRunner

testRunner类关系

@Runwith_第1张图片

自定义一个简单的testRunner的方法是继承junit默认的runner BlockJUnit4ClassRunner。

public class BlockJUnit4ClassRunner extends ParentRunner {
 
  @Override
  protected List getChildren() {
    // scan test class for methonds annotated with @Test
  }
 
  @Override
  protected Description describeChild(FrameworkMethod method) {
    // create Description based on method name
  }
 
  @Override
  protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
    if (/* method not annotated with @Ignore */) {
      // run methods annotated with @Before
      // run test method
      // run methods annotated with @After
    }
  }
}

简单的自定义:在没给测试之前打印日志。

public class MyTestRunner extends BlockJUnit4ClassRunner {
    /**
     * Creates a BlockJUnit4ClassRunner to run {@code klass}
     *
     * @param klass
     * @throws InitializationError if the test class is malformed.
     */
    public MyTestRunner(Class klass) throws InitializationError {
        super(klass);
    }

    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
        System.out.println("this is my cusstom test runner : " + method.toString());

        super.runChild(method, notifier);
    }
}

引用

  1. Understanding JUnit's Runner architecture

你可能感兴趣的:(@Runwith)