【发布时间】:2018-03-01 20:54:14
【问题描述】:
当您期望目标方法抛出异常时,这就是您编写测试的方式。
@Test(expected = myExpectedException.class)
public void Test()
{
}
如果方法没有抛出异常就成功了怎么办?有那个属性吗?
【问题讨论】:
当您期望目标方法抛出异常时,这就是您编写测试的方式。
@Test(expected = myExpectedException.class)
public void Test()
{
}
如果方法没有抛出异常就成功了怎么办?有那个属性吗?
【问题讨论】:
如果测试方法抛出异常,则认为该测试处于 ERROR 状态,不计入 PASSED 测试。 换句话说——你不需要任何特殊待遇。只需调用您要测试的方法即可。
如果您想明确表示不允许异常,可以在测试中添加ExpectedException 规则:
public class MyClassTest {
// The class under test
// Initialized here instead of in a @Before method for brevity
private MyClass underTest = new MyClass();
// Not really needed, just makes things more explicit
@Rule
public ExpectedException noExceptionAllowed = ExpectedException.none();
@Test
public void testSomeMethod() throws SomeException {
// If an exception is thrown, the test errors out, and doesn't pass
myClass.someMethod();
}
}
【讨论】:
不抛出异常并且同时不预期它总是成功 但是,如果您明确希望您的测试告诉 Spec 该方法可能会引发异常,但这次不是,您可以使用类似这样的方法
(在我的档案中找到了这段代码。我记得我从互联网上引用过它)
class MyAssertionRules {
public static void assertDoesNotThrow(FailableAction action) {
try {
action.run();
} catch (Exception ex) {
throw new Error("Unexpected Exception Thrown", ex);
}
}
}
@FunctionalInterface
interface FailableAction {
void run() throws Exception;
}
然后你可以像这样运行你的测试
public void testMethodUnderTest() {
MyAssertionRules.assertDoesNotThrow(serviceUnderTest::methodUnderTest);
}
【讨论】: