Ahmad Usama Beg
Ahmad Usama Beg

Reputation: 325

Throwing an exception from Mockito

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

Answers (2)

vaquar khan
vaquar khan

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

Makoto
Makoto

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

Related Questions