Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito exception in doThrow that looks correct

Tags:

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

interface:

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

unit test:

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

result:

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. 
like image 322
Karl K Avatar asked Aug 29 '12 22:08

Karl K


People also ask

Do you throw exception class?

You can't throw an exception in class definition. You should throw your exception in method definition or use try-catch block. Show activity on this post. throwing a specific type of Exceptions will reduce bugs because the base class Exception can handle all the types of exceptions.

Can Mockito throw exceptions on void methods?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.


1 Answers

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.

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.

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.

like image 113
Gijs Avatar answered Sep 27 '22 22:09

Gijs