为什么JUnit测试在Eclipse中运行两次? [英] Why are JUnit tests run twice from within Eclipse?

查看:835
本文介绍了为什么JUnit测试在Eclipse中运行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一个类似的问题此处



一个(不被接受) answer 指出:


测试类将始终直接启动,然后通过套件中的
link。这可以预期。


有人可以解释这是什么意思,以及是否可以防止测试运行两次。 / p>

当我使用 mvn test 从命令行运行测试时,他们只运行一次。



更新



我有一个定义如下的测试套件:

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


解决方案

Eclipse在项目级别(或程序包级别)上,Eclipse会为JUnit类(或选定的软件包)搜索所有项目的源文件夹。这些都是具有 @Test 注释的所有类,所有类都具有 @RunWith (可能还有一些)。然后对于所有这些类,它将它们作为测试运行。



由于这种行为,如果您有一个套件类引用同一项目中的测试类,则这些测试会跑两次如果你有另一个套房做同样的事情,他们会跑三次等等。要了解这个行为,请尝试运行一个包含一个测试用例的套件两次,例如:

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

这里接受的策略是定义一个项目的套件或套件,专门运行它们。不要在项目级别开始测试,但只运行选定的套件。



就Maven而言,我怀疑其默认配置仅挑选套件类并省略测试案例。如果配置不同,它将与Eclipse相同。


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

解决方案

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.

这篇关于为什么JUnit测试在Eclipse中运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆