如何测试该方法不会抛出异常?

问题描述 投票:2回答:2

当您期望目标方法抛出异常时,这就是您编写测试的方式。

@Test(expected = myExpectedException.class)
public void Test()
{

}

如果成功是在方法没有抛出异常时怎么办?这有属性吗?

java exception junit
2个回答
3
投票

如果从测试方法中抛出异常,则认为测试处于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();
    }
}

1
投票

不抛出异常并且同时没有预料到它总是成功但是如果你明确希望你的测试告诉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);
}
© www.soinside.com 2019 - 2024. All rights reserved.