自定义Junit运行程序,运行前后

时间:2017-06-26 12:22:03

标签: java junit junit4 junit-runner

在单元自定义运行器中,我想在运行测试操作之前和之后执行操作, 所以我解决了这个问题。

这样做有多扎实,是否有更简洁的方法来实现这一目标?

public class SomeCustomRunner extends BlockJUnit4ClassRunner {
    private int  m_testMethodIndex  = 0;
    private int  m_testMethodsCount = 0;
    private boolean m_sessionSetup = false;

    @Override
    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
        if(m_sessionSetup == false) {
            m_sessionSetup = true;
            beforeTestClass(); //->> DO MY STUFF HERE
        }

        super.runChild(method, notifier);

        m_testMethodIndex++;

        if(m_testMethodIndex == m_testMethodsCount) {
            afterTestClass(); //->> DO MY STUFF HERE
        }
    }

    @Override
    protected List<FrameworkMethod> getChildren() {
        List<FrameworkMethod> methods = super.getChildren();
        m_testMethodsCount = methods.size();
        return methods;
    }
}

3 个答案:

答案 0 :(得分:1)

您可以在使用@BeforeClass resp注释的方法中定义要在测试类本身之前和之后执行的操作,而不是创建单独的测试运行器。 @AfterClass

要在多个测试中重用它们,您可以轻松地从基类继承它们。

答案 1 :(得分:0)

最简单的方法是覆盖run方法,如下所示:

public class LifecycleRunner extends BlockJUnit4ClassRunner {

    public LifecycleRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override
    public void run(RunNotifier notifier) {
        beforeRunTests();
        try {
            super.run(notifier);
        } finally {
            afterRunTests();
        }
    }

    private void afterRunTests() {
        trace();
    }

    private void beforeRunTests() {
        trace();
    }

    private void trace() {
        System.out.println(Thread.currentThread().getStackTrace()[2]);
    }
}

答案 2 :(得分:0)

要完全控制测试执行,请在运行程序中安装适当的RunListener。

@Override
public void run(final RunNotifier notifier)
{
    final RunListener listener = new RunListener()
    {
        @Override
        public void testStarted(final Description description) throws Exception
        {
            // do something before each (non-ignored) Test method is executed
        }


        @Override
        public void testFinished(final Description description) throws Exception
        {
            // do something after each Test method was performed (failed or successful)
        }

        // check further listener methods yourself!

    };

    // install your listener
    notifier.addListener(listener);
    super.run(notifier);
    // and remove it again
    notifier.removeListener(listener);
}