java - Groovy Mockito NullPointerException

标签 java groovy mockito powermockito

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

相关文章:

Java应用程序在eclipse中运行,随机 "fatal errors"

java - 方法有时会捕获一个 org.hibernate.exception.JDBCConnectionException,为什么?

java - 在内存/嵌入式 SFTP 服务器中,用于在 Java 中使用私钥身份验证进行测试

Grails 数据库迁移插件 updateOnStart 不起作用

grails - 如何从 grails 中的 url 下载图像

android - 带参数的Gradle任务

java - 消息部分 MyClass 未被识别。 (它存在于服务 WSDL 中吗?)

java - Powermock withArguments 调用变量输入

java - Spring Boot 服务层单元测试中模拟原始字符串

java - 为什么我必须在 "declaring"mock 时处理异常?模拟#when