Why are JUnit tests run twice from within Eclipse?

2019-01-28 22:53发布

问题:

A similar question has already been asked here.

One (unaccepted) answer states:

the test class will always be started directly and then through the "link" in the suite. This is as expected.

Can someone explain what this actually means and whether or not it is possible to prevent the tests running twice.

When I run the tests from the command line using mvn test they only run once.

UPDATE

I have a test suite defined as follows:

@RunWith(Suite.class)
@SuiteClasses({ TestCase1.class, TestCase2.class })
public class MyTestSuite
{
}

回答1:

When you run tests in Eclipse on project level (or package level), Eclipse searches all project's source folders for JUnit classes (or selected package). These are all classes with @Test annotations and all classes with @RunWith (probably some more too). Then for all these classes it runs them as tests.

As a result of this behavior, if you have a suite class that references tests classes in the same project, these tests will run twice. If you had another suite that did the same, they would run three times and so on. To understand this behavior try running a suite that contains one test case twice, for instance:

@RunWith(Suite.class)
@SuiteClasses({ TestCase1.class, TestCase1.class })
public class TestSuite {}

Accepted strategy here is to define a suite or suites for a project an run them exclusively. Do not start tests on a project level but run selected suites only.

As far as Maven is concerned, I suspect that its default configuration only picks out suite class and omits test cases. Had it been configured differently, it would behave the same as Eclipse.



回答2:

Elipse tests 2 classes and give you 2 results. Maven tests 2 classes and give you one result with 2 sub results.

I think is somethink like this, but still most important thing is that result are positive! :) Regards!



回答3:

Same as this question https://github.com/spring-projects/spring-boot/issues/13750

Just exclude individual test cases and include the suite test cases.