【发布时间】:2020-02-16 23:59:30
【问题描述】:
对于我的一个项目,我使用 JUnit 5 来测试反射代码,这需要大量的类用于测试用例。将它们全部放在一个范围内并尝试智能地命名它们几乎是不可能的,因此我希望将测试方法和正在测试的类型都放在静态成员类中。这样做可以让我在每个测试中重用诸如X 或Y 之类的名称,并将被测试的类型保持在测试它们的代码附近。 (成员类必须是静态的,所以我可以添加接口)
如果我只是添加静态类,测试运行良好开箱即用,但在最终报告中,我最终会单独列出所有成员类,所以我希望能够将它们全部“扁平化”到报告中的单个类。
这是我想要实现的示例:(我实际上是在 Kotlin 中编写测试,但这是等效的 Java 代码)
class MethodTests {
static class WhateverName {
interface X {}
class Y implements X {}
@Test
void something_withInterfaceSupertype_shouldReturnThing() {
// ...
}
@Test
void other_withInterfaceSupertype_shouldReturnThing() {
// ...
}
}
static class WhateverOtherName {
interface X {
void m();
}
class Y implements X {
void m() {}
}
@Test
void something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing() {
// ...
}
}
// This might actually be even better, since I wouldn't need `WhateverName`
@Test // not valid, but maybe I could annotate the class instead of the method?
static class something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo {
interface X {}
class Y implements X {}
@Test
void runTest() {
// ...
}
}
}
目前,IDEA 中的测试报告最终结构如下:
- MethodTests
- someRoot_testHere
- MethodTests$WhateverName
- something_withInterfaceSupertype_shouldReturnThing
- other_withInterfaceSupertype_shouldReturnThing
- MethodTests$WhateverOtherName
- something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- MethodTests$something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
- runTest
但我希望测试报告的结构如下:
- MethodTests
- someRoot_testHere
- something_withInterfaceSupertype_shouldReturnThing
- other_withInterfaceSupertype_shouldReturnThing
- something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
我尝试在成员类上使用@DisplayName,但它只是导致报告中出现重复名称。到目前为止,我想我可能想使用一个扩展,但是在做了一些研究之后,我还没有找到任何方法来改变使用它们的报告中列出的测试类。
【问题讨论】:
-
'静态内部是一个矛盾的术语。见JLS 8.1.3。
-
@user207421 正确,我只是认为对于大多数回答这个问题的人来说,“内部阶层”会更熟悉。我修复了它,但为了任何人搜索这个问题,我恢复了它。我认为“内部阶层”只是一个更常见的搜索词。
-
你还没有到处修复它。不要滥用标准术语。