How to run a single method in a JUnit 4 test class? [duplicate]

走远了吗. 提交于 2020-01-05 02:25:11

问题


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.).

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?

Thanks in advance.


回答1:


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



回答2:


I think this can only be done with a custom TestRunner. You could pass the names of the tests you wish to run as arguments when launching your tests. A more fancier solution would be to implement a custom annotation (lets say @TestGroup), which takes a group name as argument. You could than annotate your test methods with it, giving those tests you want to run together the same group name. Again, pass the group name as argument when launching the tests. Within your test runner, collect only those methods with the corresponding group name and launch those tests.

However, the simplest solution to this is to move those tests you want to run separately to another file...



来源:https://stackoverflow.com/questions/13605774/how-to-run-a-single-method-in-a-junit-4-test-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!