JUnit 是个很著名的飞行模式测试框架,即使到了 Scala 中还是免不了要用 JUnit Style 的测试方式,基于 Spec 的方式并不处处行得通,比如想要在 Scala 中使用 JMockit 框架时。
JUnit 提供给我们有两个扩展点,Runner 和 Rule, Runner 扩展点一般被各种框架劫持了,自己搞个 @RunWith(SomeRunner.class)
可能让你无法在测试中应用框架。于是剩下了 Rule 是个更自由的扩展点,这里不讲述怎么定制自己的 Rule,而是怎么用它,怎么在 Scala 中用它。之前的一篇 JUnit 4 如何正确测试异常 中使用了 ExpectedException
这个 Rule。
Rule 的要求是: Annotates fields that reference rules or methods that return a rule. A field must be public, not static, and a subtype of TestRule
(preferred) or MethodRule
. A method must be public, not static, and must return a subtype of TestRule
(preferred) or MethodRule
. 属性或方法必须是 public 非静态的,它们的类型或返回类型必须分别是 TestRule 和 MethedRule。