Home > OS >  Mock final method in superclass
Mock final method in superclass

Time:10-05

I am creating a new service 'MyService' that extends AbstractScheduledService and MyService inherits a final method isRunning() from it.

public class MyService extends AbstractScheduledService {}

I also have a health check for 'MyService' that invokes isRunning() to see if 'MyService' is healthy.

public class MyServiceHealthcheck {
       MyService myService;
       
       @Inject
       public MyServiceHealthCheck(MyService myService) {
          this.myService = myService;
       }

       public boolean isHealthy() {
          return myService.isRunning();
       }
}

And finally, I am trying to create unit test 'MyServiceHealthcheckTest' for testing MyServiceHealthcheck

public class MyServiceHealthcheckTest {
       @Mock MyService myService;
}

The mock is initialized properly and I'm able to get expected value for methods defined in MyService but myService.isRunning() always returns a NullPointerException. What is the best way to mock isRunning() method?

CodePudding user response:

You need to configure Mockito so that mocking final classes and methods is possible. To achieve this you need to add a text file named org.mockito.plugins.MockMaker to your project src/test/resources/mockito-extensions directory. It should include a single line of text as follows: mock-maker-inline.

  • Related