首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在DrJava中测试异常?

如何在DrJava中测试异常?
EN

Stack Overflow用户
提问于 2013-08-30 18:53:18
回答 2查看 238关注 0票数 1

我是从Java开始使用DrJava的。我跟随TDD学习。我创建了一个方法来验证一些数据,对于无效的数据,这个方法应该抛出异常。

它正在按预期抛出异常。但我不确定,如何编写单元测试来期望异常。

在.net,我们有ExpectedException(typeof(exception))。有人能告诉我在DrJava中什么是等价的吗?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-30 18:55:02

如果您正在使用JUnit,您可以

代码语言:javascript
复制
@Test(expected = ExpectedException.class)
public void testMethod() {
   ...
}

有关更多细节,请查看API接口

票数 2
EN

Stack Overflow用户

发布于 2013-08-30 20:18:06

如果您只是想测试某个特定的异常类型是在您的测试方法中的某个地方抛出的,那么已经显示的@Test(expected = MyExpectedException.class)是可以的。

对于更高级的异常测试,您可以使用@Rule,以便进一步细化预期抛出异常的位置,或者添加对抛出的异常对象的进一步测试(即消息字符串等于某些期望值或包含某些期望值:

代码语言:javascript
复制
class MyTest {

   @Rule ExpectedException expected = ExpectedException.none();
   // above says that for the majority of tests, you *don't* expect an exception

   @Test
   public testSomeMethod() {
   myInstance.doSomePreparationStuff();
   ...
   // all exceptions thrown up to this point will cause the test to fail

   expected.expect(MyExpectedClass.class);
   // above changes the expectation from default of no-exception to the provided exception

   expected.expectMessage("some expected value as substring of the exception's message");
   // furthermore, the message must contain the provided text

   myInstance.doMethodThatThrowsException();
   // if test exits without meeting the above expectations, then the test will fail with the appropriate message
   }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18539710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档