Home > front end >  Mockito Throwing NullpointerException while calling doCallRealMethod
Mockito Throwing NullpointerException while calling doCallRealMethod

Time:10-04

Am using Mockito version 3.6.28 for Junit testing. Am getting Nullpointer Exception while calling the real method on the object. Its because of the dependency on the target object is not injected correctly .This is the code am using.

    public class ClassA{

    @Autowired
    LoggingService loggingService;
    
    @Autowired
    ClassB classB;

    publc void doSomething(){
        loggingService.info("info log"); // This will works fine
        classB.doSomething();
    }
}

public class ClassB{

    @Autowired
    LoggingService loggingService;
    
    public void doSomething(){        
        loggingService.info("info log"); // Nullpointer on this line since loggingService is null
    }

}

@RunWith(MockitoJUnitRunner.Silent.class)
public class TestClass{

    @InjectMocks
    ClassA classA;
    
    @Mock
    ClassB classB;
    
    @Mock
    private LoggingService loggingService;
    
    @Test
    public void testMethod(){
        doCallRealMethod().when(classB).doSomething(); 
        classA.doSomething();
        
    }
}

CodePudding user response:

Nullpointer Exceptions in Mockito are usually caused by missing dependencies as you said.

In your case ClassA's are injected accordingly, but when it comes to ClassB it is a Mock object ( i.e no dependencies are injected).

So you would have to inject the Mock's of ClassB while using ClassB.

Something like

 @Test
    public void testMethod(){

        @InjectMocks
        ClassB classB_1;

        doCallRealMethod().when(classB_1).doSomething(); 
        classA.doSomething();
        
    }

CodePudding user response:

The problem is that You are Injecting mocks only into ClassA and not into ClassB:

@InjectMocks
ClassA classA;

@Mock
private LoggingService loggingService;

@Mock
private ClassB classB;

So, the loggingService inside ClassB is null (it was not injected), and so it is throwing NullPointerException.

The thing is, if You are testing ClassA - most probably You should not call the real method of ClassB, You should mock it.

However if you have to do it, there is a way.

InelliJ is suggesting that instead of @Autowire it is better to use constructors (it is easy to do with lombok). When you have dependencies injected with constructor, it would be then much easier to pass a mock like:

private ClassB classB = new ClassB (mock(LoggingService.class));
  • Related