看起来正确的doThrow中的Mockito异常 [英] Mockito exception in doThrow that looks correct

查看:651
本文介绍了看起来正确的doThrow中的Mockito异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟一个方法来查看我是否正确处理了异常。这是我得到的。

I'm trying to mock a method to see if I handle an exception correctly. This is as far as I get.

界面:

interface SampleManager {
    void deleteVariome(String specimenId, String analysisId) throws Exception;
    // ...
}

单元测试:

// ...
SampleManger sampleManager = mock(SampleManager.class);

// below is line 753
doThrow(Exception.class).when(sampleManager).deleteVariome(sample1.getId(), analysisId);

结果:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at ...server.ArchiveManagerImplUTest.deleteVariomeFails(ArchiveManagerImplUTest.java:753)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod(); <-- this looks a log like what I did!

Hints:

 1. missing thenReturn()

 2. you are trying to stub a final method, you naughty developer! <-- I have a lot of other mocks of this interface in this test that work.


推荐答案

从我遇到的同一个问题来看,我怀疑 sample 是一个模拟器,你在其他地方存根 sample.getId()?无论如何,这在我的情况下引起了这个问题。

From an identical issue that I just ran into, I suspect that sample is a mock, and you stubbed sample.getId() elsewhere? That caused this problem in my case, anyhow.

出于某种原因,如果你传递给与一起使用的存根的一个参数,Mockito会感到不安doThrow 以这种方式是你也嘲笑的方法的结果。也许这是一种重新进行的检查,以避免无限循环,我不知道。

For some reason, Mockito gets upset if one of the arguments you pass to the stub used with doThrow in this way is the result of a method you also mocked. Perhaps it's a re-entrancy check of sorts to avoid infinite loops, I don't know.

无论如何,请尝试替换 sample.getId() 具有常量值,应该可以解决问题。你可以考虑在你的测试中使用一个常量来模拟它和它的任何进一步用途。然后,您还可以通过添加对 verify sample.getId() c>。

Regardless, try replacing sample.getId() with a constant value and that should solve the issue. You could consider using a constant declared in your test for both the mock and any further uses of it. You could then also check that sample.getId() was used by the method you're testing by adding another call to verify.

这篇关于看起来正确的doThrow中的Mockito异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆