Search code examples
javajunitjunit4junit3

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


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.


Solution

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