gpt4 book ai didi

java - Groovy Mockito NullPointerException

转载 作者:行者123 更新时间:2023-12-02 08:41:14 26 4
gpt4 key购买 nike

我有这个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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com