如何使用Mockito测试void方法

时间:2017-09-17 20:14:58

标签: junit mockito junit4

代码部分中的以下发布方法返回void。我想知道如何测试返回void的方法。 我检查了一些答案,但使用" doThrow()"传递异常,但在我的情况下,该方法不会抛出任何异常

请让我知道如何测试方法返回void?

public void setImageOnImageView(RequestCreator requestCreator, ImageView imgView) {
    requestCreator.into(imgView);
}

测试

public class ValidationTest {
    @Mock
    private Context mCtx = null;
    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Before
    public void setUp() throws Exception {
        mCtx = Mockito.mock(Context.class);
        Assert.assertNotNull("Context is not null", mCtx);
    }

    @Test
    public void setImageOnImageView() throws Exception {
        Uri mockUri = mock(Uri.class);
        RequestCreator requestCreator = Picasso.with(mCtx).load(mockUri);
        RequestCreator spyRequestCreator = spy(requestCreator);
        ImageView imageView = new ImageView(mCtx);
        ImageView spyImageView = spy(imageView);

        doThrow().when(spyRequestCreator).into(spyImageView);
        //spyRequestCreator.into(spyImageView);
    }
}

1 个答案:

答案 0 :(得分:0)

你到底想要测试什么?该测试是"当setImageOnImageView(RequestCreator, ImageView)被调用时,它会调用RequestCreator.into(ImageView)"?

如果这是您尝试测试的内容,那么您并不想测试它是否会返回无效"。相反,我会建议像:

@Test
public void itInvokesRequestCreatorIntoOnProvidedImageView() {
    RequestCreator creator = mock(RequestCreator.class);
    ImageView imageView = mock(ImageView.class);

    setImageOnImageView(creator, imageView);
    verify(creator).into(imageView);
}