我有这个java代码:
@Service
public class TestService {
@Inject
private AnotherClass anotherClass;
public boolean isEnabled() {
return anotherClass.getSomeValue().equals("true");
}
}
然后我有 Groovy 测试类:
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;
}
}
上面的测试是在Java类中的anotherClass.getSomeValue()语句上抛出java.lang.NullPointerException。看起来 TestClass 设置正确。我不明白问题出在哪里。
最佳答案
您需要注入(inject)您的模拟。
只需添加@InjectMocks
私有(private)TestService testService;
并且您不需要 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;
}
}
关于java - Groovy Mockito NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382790/