[英]Groovy Mockito NullPointerException
我有這個 java 代碼:
@Service
public class TestService {
@Inject
private AnotherClass anotherClass;
public boolean isEnabled() {
return anotherClass.getSomeValue().equals("true");
}
}
然后我有 Groovy 測試 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;
}
}
上述測試是在 Java class 中的 anotherClass.getSomeValue() 語句上拋出 java.lang.NullPointerException。 看起來 TestClass 設置正確。 我不明白問題出在哪里。
你需要注入你的模擬。 只需添加@InjectMocks
到私有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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.