Mockito SpyBean引发UnfinishedStubbingException

时间:2019-04-05 09:11:24

标签: java spring mockito

我正在尝试使用Mockito的Spy对服务进行部分模拟,重写一种方法以使其返回一致的数据以进行测试,但是该间谍没有明显的原因抛出UnfinishedStubbingException。

这是我的测试课:

@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationIT {

    private CompletableFuture<JobList> jobList;

    @SpyBean
    private Service serviceSpy;

    @Before
    public void setUp() {
        initMocks(this);

        jobList = new CompletableFuture<>();
        jobList.complete(jobList.newBuilder()
                .addAllJobs(jobTestData.getTestJob().getJobs()).build()); 

        Mockito.doReturn(jobList).when(serviceSpy).fetchJob();  
        Mockito.doNothing().when(serviceSpy).reportSuccess(Mockito.any());
    }

    @Test
    public void fetchJobCallTest() {
        Mockito.verify(serviceSpy, timeout(60000).atLeastOnce()).fetchJob();
    }

    @Test
    public void reportSuccessCallTest() {       
        Mockito.verify(serviceSpy, timeout(60000).atLeastOnce()).reportSuccess(Mockito.any());
    }
}

两项测试均失败,并且org.mockito.exceptions.misusing.UnfinishedStubbingException指向Mockito.doReturn(jobList).when(serviceSpy).fetchJob();处的Mockito.doNothing().when(serviceSpy).reportSuccess(Mockito.any());

1 个答案:

答案 0 :(得分:0)

UnfinishedStubbingException means you are not mocking properly
this is not the right way of mocking a method... Mockito.doReturn(jobList).when(serviceSpy).fetchJob();
You can try below...
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();