Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: mock method throws exception

Tags:

java

mockito

I'm trying to mock this method:

boolean login() throws SftpModuleException;

Mocking code is:

Mockito
    .when(this.sftpService.login())
    .thenReturn(true);

Since, login() throws an SftpModuleException, compiler tells me that this exception has to be handled.

Is there any work around due to this exception will never be thrown?

like image 976
Jordi Avatar asked Feb 04 '19 10:02

Jordi


People also ask

How do I ignore an exception in Mockito?

If you want to ignore a test method, use @Ignore along with @Test annotation. If you want to ignore all the tests of class, use @Ignore annotation at the class level.

Can I mock private methods using Mockito?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


2 Answers

Consider having your @Test method simply declare the exceptions being thrown, or even declaring throws Exception.

@Test
public void testFoo() throws Exception {
  // mocking and test code here
}
like image 123
orip Avatar answered Oct 13 '22 00:10

orip


I think you can add this to a method signature

@Test
public void test() throws SftpModuleException {

  Mockito
    .when(this.sftpService.login())
    .thenReturn(true);
  // code
}
like image 42
dehasi Avatar answered Oct 13 '22 00:10

dehasi