Mock测试返回为void的方法

1.使用doAnswer方法解决,代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class}) 
public class ControllerTest { 
    @Test 
    public void updateReading() throws Exception { 
        Answer<Object> answer = invocationOnMock -> invocationOnMock.getArguments();
        doAnswer(answer).when(taskModificationService)
             .changeReadingStatus(anyList(),anyByte()); 
    } 
} 

2.上面的写法有点累赘,创建了Answer对象,又什么都没做,不如直接使用doNothing比较简单明了。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class}) 
public class ControllerTest { 
    @Test 
    public void updateReading() throws Exception { 
        doNothing().when(taskModificationService).changeReadingStatus(anyList(),anyByte());
    } 
} 

其他方法请参考:https://yanbin.blog/mockito-how-to-mock-void-method/#more-7748

猜你喜欢

转载自blog.csdn.net/yshuoo/article/details/82849083