简体   繁体   中英

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.

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;
}

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM