@H_403_5@
public class DisallowUppercaseLetterAtBeginning implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
char c = context.getrequiredTestMethod().getName().charAt(0);
if (Character.isUpperCase(c)) {
throw new RuntimeException("test method names should start with lowercase.");
}
}
}
现在我想测试我的扩展按预期工作.
@H_403_5@@ExtendWith(DisallowUppercaseLetterAtBeginning.class)
class MyTest {
@Test
void validTest() {
}
@Test
void TestShouldNotBeCalled() {
fail("test should have Failed before");
}
}
如何编写测试以验证执行第二个方法的尝试是否会抛出带有特定消息的RuntimeException?
最佳答案
另一种方法可能是使用新的JUnit 5-Jupiter框架提供的工具.
原文链接:https://www.f2er.com/java/437450.html我把我在Eclipse Oxygen上用Java 1.8测试过的代码放在下面.代码缺乏优雅和简洁,但有望成为为元测试用例构建强大解决方案的基础.
请注意,这实际上是JUnit 5的测试方法,我推荐你the unit tests of the Jupiter engine on Github.
@H_403_5@public final class DisallowUppercaseLetterAtBeginningTest {
@Test
void testIt() {
// Warning here: I checked the test container created below will
// execute on the same thread as used for this test. We should remain
// careful though,as the map used here is not thread-safe.
final MapFailed,events.get("TestShouldNotBeCalled()").getStatus());
Throwable t = events.get("TestShouldNotBeCalled()").getThrowable().get();
assertEquals(RuntimeException.class,t.getClass());
assertEquals("test method names should start with lowercase.",t.getMessage());
}
虽然有点冗长,但这种方法的一个优点是它不需要在同一个JUnit容器中进行模拟和执行测试,这将在以后用于实际单元测试.
通过一些清理,可以实现更易读的代码.同样,JUnit-Jupiter资源可以成为灵感的重要来源.