【问题标题】:How to test a void method using Mockito如何使用 Mockito 测试 void 方法
【发布时间】:2017-09-17 20:14:58
【问题描述】:

下面在代码部分发布的方法返回 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);
    }
}

【问题讨论】:

    标签: junit mockito junit4


    【解决方案1】:

    您到底想测试什么?那个测试是“当setImageOnImageView(RequestCreator, ImageView)被调用时,它调用RequestCreator.into(ImageView)”?

    如果这就是您要测试的内容,那么您不想测试它是否“返回 void”。相反,我会推荐类似的东西:

    @Test
    public void itInvokesRequestCreatorIntoOnProvidedImageView() {
        RequestCreator creator = mock(RequestCreator.class);
        ImageView imageView = mock(ImageView.class);
    
        setImageOnImageView(creator, imageView);
        verify(creator).into(imageView);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多