简体   繁体   English

如何在返回void并引发异常的方法上抛出Throw或thenThrow

[英]How to doThrow or thenThrow on method that returns void and throws an exception

I have a method process that returns void and also may throw an exception. 我有一个返回无效的方法process ,并且可能会引发异常。 I want to verify how does behave other method run while calling process and handles an exception if it occurs. 我想验证其他方法在调用process如何run并处理异常(如果发生)。

I've tried to use doThrow() but it tells "Checked exception is invalid for this method!". 我尝试使用doThrow()但是它告诉“已检查的异常对该方法无效!”。 Then I've tried to use thenThrow() but it needs a not void function. 然后,我尝试使用thenThrow()但它需要一个不无效的函数。

Code: 码:

public void run() {
    for (var billet : getBillets()) {
        try {
            process(billet);
            billet.status = "processed";
        } catch (Exception e) {
            billet.status = "error";
        }

        billet.update();
    }
}

public void process(Billet billet) throws Exception {
    var data = parse(billet.data); // may throw an exception
    var meta = data.get("meta"); // may throw an exception

    // ... more parsing ...

    new Product(meta).save();
    new Item(meta).save();

    // ... more operations ...
};

Test: 测试:

var billet1 = new Billet();
var billet2 = new Billet();

doThrow(new Exception()).when(myInctance).process(billet2);
myInctance.run();
assertEquals("processed", billet1.status);
assertEquals("error", billet2.status);

// ... some checks ...

I expect the test would succeeded. 我希望测试会成功。

This is the correct way to tell a mock to throw an exception: 这是告诉模拟程序抛出异常的正确方法:

Mockito.doThrow(new SomeException()).when(mock).doSomething()

As Hulk stated in the comments, this exception needs to match the method signature, otherwise, you will get a MockitoException("Checked exception is invalid for this method!") 如Hulk在评论中所述,此异常需要与方法签名匹配,否则,您将获得MockitoException("Checked exception is invalid for this method!")

You could get around that exception by throwing some type of RuntimeException . 您可以通过抛出某种RuntimeException来解决该异常。 Lastly, you should try to avoid using a generic Exception . 最后,您应该尝试避免使用泛型Exception It is far more useful to throw an appropriate named exception. 抛出适当的命名异常要有用得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM