Groovy Mockito NullPointerException

问题描述 投票:0回答:1

我有这个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已正确设置。我不明白问题出在哪里。

java groovy mockito powermockito
1个回答
0
投票

您需要注入您的模拟。只需添加@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;
}

} 
© www.soinside.com 2019 - 2024. All rights reserved.