How can I mock a void method to throw an exception?

穿精又带淫゛_ 提交于 2019-12-04 23:56:44

Since none of your classes are final, you can use "pure mockito" without resorting to PowerMockito:

final CacheWrapper wrapper = Mockito.spy(new CacheWrapper());

Mockito.doThrow(something)
    .when(wrapper).putInSharedMemory(Matchers.any(), Matchers.any());

Note that "method arguments" to a stub are in fact argument matchers; you can put specific values (if not "surrounded" by a specific method it will make a call to .equals()). So, you can guide the stub's behavior differently for different arguments.

Also, no need for any kind of .replay() with Mockito, which is very nice!

Finally, be aware that you can doCallRealMethod() as well. After that, it depends on your scenarios...

(note: last mockito version available on maven is 1.10.17 FWIW)

nhylated

Are you using EasyMock or Mockito? Both are different frameworks.

PowerMockito is a superset (or more of a supplement) that can be used with both these frameworks. PowerMockito allows you to do things that Mockito or EasyMock don't.

Try this for stubbing void methods to throw exceptions:

EasyMock:

// First make the actual call to the void method.
cacheWrapper.putInSharedMemory("key", "value");
EasyMock.expectLastCall().andThrow(new RuntimeException());

Check:

Mockito:

 // Create a CacheWrapper spy and stub its method to throw an exception.
 // Syntax for stubbing a spy's method is different from stubbing a mock's method (check Mockito's docs).
 CacheWrapper spyCw = spy(new CacheWrapper()); 
 Mockito.doThrow(new RuntimeException())
     .when(spyCw)
     .putInSharedMemory(Matchers.any(), Matchers.any());

 SomeClient sc = new SomeClient();
 sc.setCacheWrapper(spyCw);

 // This will call spyCw#putInSharedMemory that will throw an exception.
 sc.getEntity("key");

Use expectLastCall, like:

    cacheWrapper.putInSharedMemory(EasyMock.anyObject(), EasyMock.anyObject())
    EasyMock.expectLastCall().andThrow(new RuntimeException("This is an intentional Exception")).anyTimes();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!