Prevent junit tests from running twice

2019-08-15 09:16发布

问题:

There are many similar questions to my questions,but there is no clear answer for it! My tests are failing because they are running once inside suite and once alone. And I need them to run only once inside suite. This is my suite:

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class, Test2.class})
{
.....
}

I am running the test from the command line with command test.

Has anyone found a solution for this?

回答1:

I use the following setup to run tests with JUnit, parallel, and they run only once:

@RunWith(ParallelSuite.class)
@SuiteClasses({ Test1.class, Test2.class })
public class AllTests {

}

And I have a ParallelSuite.class:

package tests;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.internal.runners.*;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runners.model.RunnerScheduler;

public class ParallelSuite extends Suite {
    public ParallelSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError  {

        super(klass, builder);

        setScheduler(new RunnerScheduler() {

            private final ExecutorService service = Executors.newFixedThreadPool(4);

            public void schedule(Runnable childStatement) {
                service.submit(childStatement);
            }

            public void finished() {
                try {
                    service.shutdown();
                    service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace(System.err);
                }
            }
        });
    }
}