本文介绍了如何在JUnit 4测试类中运行单个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过所有类似的问题,但我认为,没有一个问题对此给出可靠的答案.我有一个测试类(JUnit 4但也对JUnit 3感兴趣),我想以编程/动态方式(而不是从命令行)从这些类中运行单独的测试方法.说,有5种测试方法,但我只想运行2种.如何以编程/动态方式实现此目的(而不是从命令行,Eclipse等).

I have looked at all the similar questions, but in my opinion, none of them give a solid answer to this. I have a test class (JUnit 4 but also interested in JUnit 3) and I want to run individual test methods from within those classes programmatically/dynamically (not from the command line). Say, there are 5 test methods but I only want to run 2. How can I achieve this programmatically/dynamically (not from the command line, Eclipse etc.).

此外,在测试类中有时还会有一个带有@Before注释的方法.因此,在运行单独的测试方法时,@Before也应事先运行.如何克服?

Also, there is the case where there is a @Before annotated method in the test class. So, when running an individual test method, the @Before should run beforehand as well. How can that be overcome?

谢谢.

推荐答案

这是一个简单的单方法运行器.它基于JUnit 4框架,但可以运行任何方法,不一定要使用@Test注释

This is a simple single method runner. It's based on JUnit 4 framework but can run any method, not necessarily annotated with @Test

    private Result runTest(final Class<?> testClazz, final String methodName)
            throws InitializationError {
        BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(testClazz) {
            @Override
            protected List<FrameworkMethod> computeTestMethods() {
                try {
                    Method method = testClazz.getMethod(methodName);
                    return Arrays.asList(new FrameworkMethod(method));

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        Result res = new Result();
        runner.run(res);
        return res;
    }

    class Result extends RunNotifier {
        Failure failure;

        @Override
        public void fireTestFailure(Failure failure) {
            this.failure = failure;
        };

        boolean isOK() {
            return failure == null;
        }

        public Failure getFailure() {
            return failure;
        }
    }

这篇关于如何在JUnit 4测试类中运行单个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 14:04
查看更多