0

We've got a class with a method with an transactional annotation

public class MyHandler extends BaseHandler {

    @Transactional
    public void annotatedMethod(String parameter) throws Exception {
    }

As soon as we try to make a test using mockito and its annotations

@InjectMocks
private Controller controller;

@Mock
private MyHandler myHandler;

we have a null pointer exception when executing the following line

Mockito.doCallRealMethod().when(myHandler).annotatedMethod(Matchers.any());

We have tried to use the same solution as in Transactional annotation avoids services being mocked with no luck.

We're new with mockito, we have no idea how to solve this. Any clues?

Thank you very much, Elena

Elena
  • 501
  • 1
  • 6
  • 15
  • Hi Elena, is `MyHandler` the class under test? If so, then mocking it might not work. The `@Transactional` annotation won't affect the behaviour of `Mockito` when used as described. It's hard to know exactly what the root cause of your problem is without some error output. My guess is that the _real method_ you're delegating to, relies on other methods within `MyHandler` and gets a null back from them when calling them on the mock. When you don't set up alternatives, all functions on mockito objects return null, false, 0, etc. – Ashley Frieze Dec 03 '18 at 07:38
  • Helllo Ashley, I've solved the issue, it was not related with the annotation.It was that Mockito was returning null. Thanks for your help – Elena Dec 07 '18 at 10:22

1 Answers1

1

you can try this way to mock the data. I have the similar NullPointerException and this way helped me.

@InjectMocks
private Controller controller;

@Mock
private MyHandler myHandler;

@Test
void testingMethod() {
    when(myHandler.annotatedMethod(Mockito.any())).thenReturn("something");
}
infD
  • 43
  • 7