JUnit5测试可以在Maven上正常工作,但不能在Eclipse中运行,“在测试运行器’JUnit 5’中找不到任何测试。”

JUnit5 tests work fine with maven but not when run through Eclipse, “No tests found with test runner 'JUnit 5'.”

我得到一个弹出窗口,标题为"无法运行测试",并显示消息"测试运行器'JUnit 5'未找到测试"。当我尝试通过Run As > JUnit Test用Eclipse运行JUnit 5测试时。

我有两个与测试相关的文件。一个是测试套件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...

import org.junit.jupiter.api.BeforeAll;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SelectPackages("com.foo.stufftotest")

public class TestSuite {
    @BeforeAll
    public static void setup() {
        ...

另一个包含"实际"测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.foo.stufftotest;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

import com.foo.TestSuite;
import com.foo.business.mechanics.LogicStuff1;

public class BusinessTest {
    @Test
    public void testLogic1() {
        ...
    }

    @Test
    public void testLogic2() {
        ...
    }

    ...

所有testLogicN()方法都依赖于TestSuite.setup()中完成的设置。如果setup()没有运行,则将有很多空值,并且事情会失败也就不足为奇了。当我尝试从项目的上下文菜单运行JUnit时,将触发所有测试,并且所有测试都会失败。该套件似乎无法识别。当我尝试从TestSuite.java的上下文菜单专门运行JUnit时,最终遇到在问题顶部提到的错误。

但是,当我在项目上运行maven test时,套件被正确触发,并且所有测试均通过。因此,代码本身似乎不是问题。

我不记得JUnit 4有这个问题,尽管我从未在这个特定项目中使用JUnit 4。

我使用Eclipse是否错误,还是使用JUnit5错误?解决的方法是什么?


尽管我的单元测试已使用org.junit.jupiter正确注释,但我在Eclipse Oxygen 4.7.1中遇到了相同的问题。

我使用了Maven > Update Project并选择了Update project configuration from pom.xml,但是即使我认为这会弥补我在pom中具有JUnit5依赖关系这一事实也没有做任何事情。

我的解决方案:

  • 打开Java Build Path,选择Libraries选项卡,然后选择Add Library
  • 选择JUnit
  • 选择JUnit5作为JUnit库版本。
  • 添加后,我便能够从Eclipse手动执行测试。但是我仍然不确定为什么没有自动添加。


    I'm getting a pop-up window with title"Could not run test" and message"No tests found with test runner 'JUnit 5'." when I try to run JUnit 5 tests with Eclipse via Run As > JUnit Test.

    这是因为TestSuite实际上不是JUnit 5测试类。由于它用@RunWith注释(来自JUnit 4),因此它是JUnit 4测试类。为了避免在Eclipse中弹出窗口,只需单击"运行配置",然后选择JUnit 4而不是JUnit 5来运行测试类。

    您遇到的另一个问题是@BeforeAll是JUnit Jupiter的注释。因此,在带有@RunWith(JUnitPlatform.class)注释的类中根本不支持它(除非该类也恰好包含JUnit Jupiter的@Test方法)。因此,您将必须找到一种替代方法来执行"设置"代码。