如何在返回 void 并引发异常的方法上执行 doThrow 或 thenThrow

Aun*_*mag 4 java mockito

我有一个process返回 void 的方法,也可能引发异常。我想验证其他方法run在调用时的行为方式process以及发生异常时的处理方式。

我尝试使用doThrow(),但它告诉我“检查的异常对此方法无效!”。然后我尝试使用thenThrow()但它需要一个非空函数。

代码:

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 ...
};
Run Code Online (Sandbox Code Playgroud)

测试:

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 ...
Run Code Online (Sandbox Code Playgroud)

我预计测试会成功。

Phi*_*nan 6

这是告诉模拟抛出异常的正确方法:

Mockito.doThrow(new SomeException()).when(mock).doSomething()
Run Code Online (Sandbox Code Playgroud)

正如Hulk在评论中所说,这个异常需要与方法签名匹配,否则,你会得到一个MockitoException("Checked exception is invalid for this method!")

您可以通过抛出某种类型的RuntimeException. 最后,您应该尽量避免使用通用的Exception. 抛出适当的命名异常要有用得多。