0

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

这样做有多扎实,有没有更干净的方法来实现这一目标?

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

3 回答 3

2

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

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

于 2017-06-26T12:34:48.990 回答
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]);
    }
}
于 2017-06-26T16:53:45.480 回答
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);
}
于 2018-12-10T14:11:53.460 回答