【问题标题】:how to test picasso using unit-test and mockito如何使用单元测试和模拟测试毕加索
【发布时间】:2017-09-17 09:18:53
【问题描述】:

我正在学习如何在 android studio 中进行单元测试。如下图,我想在代码部分测试一下下面显示的两种方法。

你能帮助并指导我如何测试这个方法吗?

代码

public RequestCreator requestCreatorFromUrl(String mPicUrl) 
{
    return Picasso.with(mCtx).load(mPicUrl);
}

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

我的尝试

@Test
public void whenRequestCreatorFromUrlTest() throws Exception {
    Picasso mockPicasso = mock(Picasso.class);
    File mockFile = mock(File.class);

    Assert.assertNotNull("returned Request creator is not null",    
 mockPicasso.load(mockFile));
}

【问题讨论】:

    标签: android junit mocking mockito junit4


    【解决方案1】:

    您无法测试的第一种方法,您必须验证 Mockito 不支持的静态方法的调用。 您可以将方法拆分为

    public RequestCreator requestCreator() {
        return Picasso.with(mCtx); 
    }
    

    public void load(RequestCreator requestCreator, String picUrl) {
       requestCreator.load(picUrl)
    }
    

    并测试load(...) 方法。

    第二种方法:

    模拟requestCreator。模拟imageView。 使用您的模拟对象调用该方法。 然后验证 requestCreator.into(...) 是否使用提供的参数调用:

    Mockito.verify(requestCreator).into(imageView); 
    

    【讨论】:

    • 我尝试测试加载方法如下:public void whenRequestCreatorFromUrl() throws Exception { ImageView mockedImageView = Mock (ImageView.class); RequestCreator requestCreator = Mock (new RequestCreator.class); } 但我收到错误..你能帮帮我吗
    • 我正在尝试按照您在回答中的说明测试加载方法,但是 .load() 方法不是 requestCreator 对象的属性??!!
    • 检查 with(context) 返回的内容并使用它。
    • .load() 方法是 Picasso 对象的属性,所以我做了以下操作来模拟 Picasso 对象:public void whenRequestCreatorFromUrlTest() throws Exception { Picasso mockPicasso = Mock(Picasso.with(mCtx)); } 但它确实有效
    • @user2121Picasso mockPicasso = Mock(Picasso.class);就像你嘲笑的其他对象一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多