Gradle 找不到 JUnit 测试

Gradle cannot find JUnit tests

在Java中,我有以下测试:

import org.junit.jupiter.api.Test;

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

abstract class MyClassTest {
    @Test
    static void testTwoPlusTwoIsFour() {
        assertEquals(4, 2 + 2);
    }

    @Test
    static void testMinusOneThatsThree() {
        assertEquals(3, -1);
    }
}

运行 gradle build 给我以下输出:

Test run finished after 95 ms
        [         1 containers found      ]
        [         0 containers skipped    ]
        [         1 containers started    ]
        [         0 containers aborted    ]
        [         1 containers successful ]
        [         0 containers failed     ]
        [         0 tests found           ]
        [         0 tests skipped         ]
        [         0 tests started         ]
        [         0 tests aborted         ]
        [         0 tests successful      ]
        [         0 tests failed          ]

似乎 Gradle 在我的任何测试 类 中找不到任何测试。

事实证明,

Gradle 找不到 staticprivateabstract class.

中的测试

以下方法访问修饰符对测试方法有效:

  • package-private(无修饰符)
  • protected
  • public

以下 class 访问修饰符对 测试有效 class:

  • package-private(无修饰符)
  • public

以下关键字测试无效:

  • abstract
  • static
  • private

只需从测试中删除 abstractstatic 关键字即可解决所有问题:

import org.junit.jupiter.api.Test;

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

class MyClassTest {
    @Test
    void testTwoPlusTwoIsFour() {
        assertEquals(4, 2 + 2);
    }

    @Test
    void testMinusOneThatsThree() {
        assertEquals(3, -1);
    }
}

Gradle 输出:

Test run finished after 158 ms
        [         2 containers found      ]
        [         0 containers skipped    ]
        [         2 containers started    ]
        [         0 containers aborted    ]
        [         2 containers successful ]
        [         0 containers failed     ]
        [         2 tests found           ]
        [         0 tests skipped         ]
        [         2 tests started         ]
        [         0 tests aborted         ]
        [         1 tests successful      ]
        [         1 tests failed          ]