【发布时间】:2017-07-21 15:22:25
【问题描述】:
我是Junit4的新手,我想知道是否有一些注释可以将一个类标记为测试类,就像使用一样
@Test 将方法标记为测试方法。
【问题讨论】:
-
为什么需要一个注解来将一个类标记为测试类?你想通过类似于scenario depicted in this thread?的测试套件动态加载和执行这些
我是Junit4的新手,我想知道是否有一些注释可以将一个类标记为测试类,就像使用一样
@Test 将方法标记为测试方法。
【问题讨论】:
您可以在类级别使用@Category 注解,例如:
@Category({PerformanceTests.class, RegressionTests.class})
public class ClassB {
@Test
public void test_b_1() {
assertThat(1 == 1, is(true));
}
}
我从https://www.mkyong.com/unittest/junit-categories-test/引用了这个例子
此外,如果您使用 JUnit 运行 Spring 测试、Mockito 测试,那么您必须在类级别使用 @RunWith 注释。
例如在 Spring 启动测试中我使用这个:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class ControllerTest {
在我使用的 Mockito(没有弹簧测试)测试中:
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
【讨论】:
注释@TestOnly,但它确实带有警告,如下所示。
import org.jetbrains.annotations.TestOnly;
警告
/**
* A member or type annotated with TestOnly claims that it should be used from testing code only.
* <p>
* Apart from documentation purposes this annotation is intended to be used by static analysis tools
* to validate against element contract violations.
* <p>
* This annotation means that the annotated element exposes internal data and breaks encapsulation
* of the containing class; the annotation won't prevent its use from production code, developers
* won't even see warnings if their IDE doesn't support the annotation. It's better to provide
* proper API which can be used in production as well as in tests.
*/
解决方法
如果有我专门用于测试的代码或类,并且需要在发布时删除它们,我会使用 Android Studio 添加自定义 TODO(不确定其他 IDE 是否具有相同的功能),请按照下面的屏幕截图在底部的 TODO 选项卡中,您将在左侧看到每个自定义 TODO 的过滤器。这绝不是最好的方法,但我发现它是在发布时删除代码的最快手动方法。
P.S 我知道这张截图中的图案有些混乱。
【讨论】: