如何通过重新抛出异常来测试代码?

How to test the code with rethrowing exceptions?

我的 android 应用程序中有一段代码捕获一个异常并将其作为另一个从 RuntimeException 扩展而来的自定义异常重新抛出。而且似乎无法测试。

看看下面的代码:

 try { ... } catch (MalformedURLException e) {
     throw new CustomMalformedDataException(downloadUrlString, e);
 }

当我尝试测试异常情况时,我写:

@Test(expected = CustomMalformedDataException.class)
public void exceptionsTest() throws Exception {
    <code triggering the exception>
}

但是我得到了Test running failed: Instrumentation run failed due to 'java.net.MalformedURLException'

当我写的时候:

@Test(expected = MalformedURLException.class)
public void exceptionsTest() throws Exception {
    <code triggering the exception>
}

我得到java.lang.Exception: Unexpected exception, expected<java.net.MalformedURLException> but was<CustomMalformedDataException>

那么我应该如何测试这个案例?

异常代码class:

public class CustomMalformedDataException extends RuntimeException {

    public CustomMalformedDataException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomMalformedDataException(String url, MalformedURLException cause) {
        super("The package has an invalid \"downloadUrl\": " + url, cause);
    } 
}

更新:似乎无论哪种方式,测试都会在初始异常被抛出时停止执行,即使它被捕获了。但是如果这个异常是预期的,执行将继续并抛出另一个异常,这已经是预期的

所以我尝试了你的代码并得到了一个不同的错误,所以我不能给你答案,但我有一种测试错误的方法我更喜欢使用 JUnit 来获得你需要的结果

@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public void testExceptionOccurs() throws Exception {
    exception.expect(CustomMalformedDataException.class);
    //code that casues exception to happen
}

我已经 运行 这很多次了,当我需要测试我的异常是否发生时,它没有任何问题。我希望这至少有助于为您提供编写异常测试的解决方案。

如果你真的需要测试 RuntimeException 然后让你的测试抛出 RuntimeException 而不是 Exception