Reputation: 325
I want to throw a ContentIOException
from a method whose signature look like this.
public void putContent(InputStream is) throws ContentIOException.
When I try to throw ContentIOException
from Mockito like such:
when(StubbedObject.putContent(contentStream)).thenThrow(ContentIOException.class);
I get the following compilation error:
The method when(T) in the type Mockito is not applicable for the arguments (void).
What am I doing wrong?
Upvotes: 32
Views: 51884
Reputation: 11479
You can use following code
when(testRepositoryMock.findOne(123)).thenThrow(new NullPointerException());
Then after you can check your logic
String erroResponse= service.testMethodForResponse(accountNum);
JSONObject jsonObj = new JSONObject(erroResponse);
String _acNo = jsonObj.getString("accountNum");
assertEquals(accountNum, _acNo);
}
If you are using Spring boot then add top of class
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
Inside of class you need to inject object
@InjectMocks //actual object you want to get test coverage
private TestService testService;
@Mock //Mock object which call by actual object for mocking
private testRepository testRepositoryMock;
Reference link :http://www.baeldung.com/mockito-behavior
Upvotes: 0
Reputation: 106498
Take a look at this reference in the official API. You want to reverse the way your call is made and adjust the argument too, since this is a void
method that you expect to throw an exception.
doThrow(new ContentIOException()).when(StubbedObject).putContent(contentStream);
Upvotes: 46