Search code examples
javagroovymockitopowermockito

Groovy Mockito NullPointerException


I have this java code:

@Service
public class TestService {
    @Inject
    private AnotherClass anotherClass;

    public boolean isEnabled() {
        return anotherClass.getSomeValue().equals("true");
    }

} 

Then I have the Groovy test class:

class TestServiceTest {
    @Mock
    private AnotherClass anotherClass;

    private TestService testService;

    @Before
    void initMock() {
        MockitoAnnotations.initMocks(this)
        testService = new TestService()
    }

    void isEnabledTest() {
        when(anotherClass.getSomeValue()).thenReturn("true")
        assert testService.isEnabled() == true;
    }

} 

The above test is throwing java.lang.NullPointerException on anotherClass.getSomeValue() statement in Java class. Looks like the TestClass is setup properly. I don't understand where is the problem.


Solution

  • You need to inject your mocks. just add @InjectMocks

    to private TestService testService;

    And you won't need testService = new TestService();

    class TestServiceTest {
    @Mock
    private AnotherClass anotherClass;
    
    @InjectMocks
    private TestService testService;
    
    @Before
    void initMock() {
        MockitoAnnotations.initMocks(this)
    }
    
    void isEnabledTest() {
        when(anotherClass.getSomeValue()).thenReturn("true")
        assert testService.isEnabled() == true;
    }
    
    }