Groovy Mockito NullPointerException
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 = 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 代码:
@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 = 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;
}
}