我是从Java开始使用DrJava的。我跟随TDD学习。我创建了一个方法来验证一些数据,对于无效的数据,这个方法应该抛出异常。
它正在按预期抛出异常。但我不确定,如何编写单元测试来期望异常。
在.net,我们有ExpectedException(typeof(exception))。有人能告诉我在DrJava中什么是等价的吗?
谢谢
发布于 2013-08-30 18:55:02
如果您正在使用JUnit,您可以
@Test(expected = ExpectedException.class)
public void testMethod() {
...
}有关更多细节,请查看API接口。
发布于 2013-08-30 20:18:06
如果您只是想测试某个特定的异常类型是在您的测试方法中的某个地方抛出的,那么已经显示的@Test(expected = MyExpectedException.class)是可以的。
对于更高级的异常测试,您可以使用@Rule,以便进一步细化预期抛出异常的位置,或者添加对抛出的异常对象的进一步测试(即消息字符串等于某些期望值或包含某些期望值:
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
}
}https://stackoverflow.com/questions/18539710
复制相似问题