【问题标题】:How to run a single method in a JUnit 4 test class? [duplicate]如何在 JUnit 4 测试类中运行单个方法? [复制]
【发布时间】:2012-11-16 08:17:35
【问题描述】:

我已经查看了所有类似的问题,但在我看来,没有一个给出可靠的答案。我有一个测试类(JUnit 4,但也对 JUnit 3 感兴趣),我想从这些类中以编程/动态方式(而不是从命令行)运行各个测试方法。比如说,有 5 种测试方法,但我只想运行 2 种。我怎样才能以编程/动态方式实现这一点(而不是从命令行、Eclipse 等)。

另外,还有在测试类中有@Before注解方法的情况。因此,在运行单个测试方法时,@Before 也应该预先运行。如何克服?

提前致谢。

【问题讨论】:

    标签: java junit junit4 junit3


    【解决方案1】:

    这是一个简单的单一方法运行器。它基于 JUnit 4 框架,但可以运行任何方法,不必使用 @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】:

      我认为这只能通过自定义TestRunner 来完成。您可以在启动测试时将希望运行的测试名称作为参数传递。一个更好的解决方案是实现一个自定义注释(比如说@TestGroup),它以组名作为参数。您可以用它来注释您的测试方法,为您想要一起运行的那些测试提供相同的组名。同样,在启动测试时将组名作为参数传递。在您的测试运行程序中,仅收集具有相应组名的方法并启动这些测试。

      但是,最简单的解决方案是将您想要单独运行的那些测试移动到另一个文件中...

      【讨论】:

        猜你喜欢
        • 2013-11-24
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-23
        • 1970-01-01
        • 2011-01-30
        相关资源
        最近更新 更多