android - 使用 Mockito 进行单元测试 Retrofit api 调用 - ArgumentCaptor

标签 android mockito retrofit2

如果我的问题看起来重复,请原谅我,但我不知道如何测试改造 API 调用。 build.gradle 在应用层

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile("com.android.support.test.espresso:espresso-core:$rootProject.ext.expressoVersion", {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
    compile "com.jakewharton:butterknife:$rootProject.ext.butterKnifeVersion"
    annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.ext.butterKnifeVersion"

    // Dependencies for local unit tests
    testCompile "junit:junit:$rootProject.ext.junitVersion"
    testCompile "org.mockito:mockito-all:$rootProject.ext.mockitoVersion"
    testCompile "org.hamcrest:hamcrest-all:$rootProject.ext.hamcrestVersion"
    testCompile "org.powermock:powermock-module-junit4:$rootProject.ext.powerMockito"
    testCompile "org.powermock:powermock-api-mockito:$rootProject.ext.powerMockito"
    compile "com.android.support.test.espresso:espresso-idling-resource:$rootProject.ext.espressoVersion"

    // retrofit, gson
    compile "com.google.code.gson:gson:$rootProject.ext.gsonVersion"
    compile "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofitVersion"
    compile "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofitVersion"
}

build.gradle 在项目级别有这个额外的内容

//在一个地方定义版本

ext {
    // Sdk and tools
    minSdkVersion = 15
    targetSdkVersion = 25
    compileSdkVersion = 25
    buildToolsVersion = '25.0.2'

    supportLibraryVersion = '23.4.0'
    junitVersion = '4.12'
    mockitoVersion = '1.10.19'
    powerMockito = '1.6.2'
    hamcrestVersion = '1.3'
    runnerVersion = '0.5'
    rulesVersion = '0.5'
    espressoVersion = '2.2.2'
    gsonVersion = '2.6.2'
    retrofitVersion = '2.0.2'
    butterKnifeVersion = '8.5.1'
    expressoVersion = '2.2.2'
}

主 Activity

public class MainActivity extends AppCompatActivity implements MainView {

    @BindView(R.id.textViewApiData)
    TextView mTextViewApiData;
    @BindView(R.id.progressBarLoading)
    ProgressBar mProgressBarLoading;

    private MainPresenter mMainPresenter;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initializeComponents();
    }

    private void initializeComponents() {
        mMainPresenter = new MainPresenter(this);
        mMainPresenter.presentDataFromApi();
    }

    @Override
    public void onResponseReceived(final String response) {
        mTextViewApiData.setText(response);
    }

    @Override
    public void onErrorReceived(final String message) {
        mTextViewApiData.setText(message);
    }

    @Override
    public void showProgressDialog(final boolean enableProgressDialog) {
        mProgressBarLoading.setVisibility(enableProgressDialog ? View.VISIBLE : View.GONE);
    }
}

主视图

public interface MainView {

    void onResponseReceived(String response);

    void onErrorReceived(String message);

    void showProgressDialog(boolean enableProgressDialog);
}

API 客户端

public class ApiClient {

    private static Retrofit sRetrofit;
    public static Retrofit getInstance() {
        if (sRetrofit == null) {
            sRetrofit = new Retrofit.Builder()
                    .baseUrl(Constants.Urls.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return sRetrofit;
    }
}

演示者

public class MainPresenter {
    private final MainView mMainView;
    private final Call<List<UserResponse>> mCallListUserResponse;

    public MainPresenter(final MainView mainView) {
        this.mMainView = mainView;
        final ApiInterface apiInterface = ApiClient.getInstance().create(ApiInterface.class);
        mCallListUserResponse = apiInterface.getUsers();
    }

    public void presentDataFromApi() {
        mMainView.showProgressDialog(true);
        mCallListUserResponse.enqueue(new Callback<List<UserResponse>>() {
            @Override
            public void onResponse(final Call<List<UserResponse>> call,
                                   final Response<List<UserResponse>> response) {
                mMainView.onResponseReceived(Constants.DummyData.SUCCESS);
                mMainView.showProgressDialog(false);
            }

            @Override
            public void onFailure(final Call<List<UserResponse>> call, final Throwable t) {
                mMainView.onErrorReceived(Constants.DummyData.ERROR);
                mMainView.showProgressDialog(false);
            }
        });
    }
}

API接口(interface)

public interface ApiInterface {
    @GET(Constants.Urls.USERS)
    Call<List<UserResponse>> getUsers();
}

常量

public class Constants {
    public class Urls {
        public static final String BASE_URL = "https://jsonplaceholder.typicode.com";
        public static final String USERS = "/users";
    }
}

这就是我正在尝试做的,但它不起作用。测试用例现在将通过,因为我已经评论了最后一行中的 3 行。取消注释这些行后,您可以查看错误。
测试用例

public class MainPresenterTest {

    @InjectMocks
    private MainPresenter mMainPresenter;
    @Mock
    private MainView mMockMainView;
    @Mock
    private Call<List<UserResponse>> mUserResponseCall;
    @Captor
    private ArgumentCaptor<Callback<List<UserResponse>>> mArgumentCaptorUserResponse;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void presentDataFromApiTest() throws Exception {
        mMainPresenter.presentDataFromApi();
        verify(mMockMainView).showProgressDialog(true);
//        verify(mUserResponseCall).enqueue(mArgumentCaptorUserResponse.capture());
//        verify(mMockMainView).onResponseReceived(Constants.DummyData.SUCCESS);
//        verify(mMockMainView).showProgressDialog(false);
    }
}

日志

Wanted but not invoked:
mUserResponseCall.enqueue(
    <Capturing argument>
);
-> at com.example.ranaranvijaysingh.testingdemo.presenters.MainPresenterTest.presentDataFromApiTest(MainPresenterTest.java:69)
Actually, there were zero interactions with this mock.

最佳答案

您的代码在语法上看起来是正确的。但是,我怀疑 @InjectMock 无法将模拟对象注入(inject)最终实例变量。当您调用 mMainPresenter.presentDataFromApi() 时,下面的变量可能被用作真实实例:

private final Call<List<UserResponse>> mCallListUserResponse;

您应该尝试手动将 mock 变量注入(inject)此类并分配给 mCallListUserResponse 以便能够从 mockito 实例化中获益。

可能值得尝试以下步骤:

  1. 将 MainPresenter 中的变量 mCallListUserResponse 设为非 final。

  2. 在类 MainPresenter 中添加如下方法:

    void setUserResponseCall(调用> userResponse){ mCallListUserResponse = 用户响应;

  3. 现在在测试类中执行以下操作:

如下修改你的测试

@Test
public void presentDataFromApiTest() throws Exception {
        //Set mock instance of the user response
        mMainPresenter.setUserResponseCall(mUserResponseCall);

        //real object call to presentDataFromApi();
        mMainPresenter.presentDataFromApi();

        verify(mMockMainView).showProgressDialog(true);    
      verify(mUserResponseCall).enqueue(mArgumentCaptorUserResponse.capture());
    }

希望对您有所帮助。

关于android - 使用 Mockito 进行单元测试 Retrofit api 调用 - ArgumentCaptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42299029/

相关文章:

android - 如何在按下任何项目时应用透明度(焦点?)(就像谷歌那样)?

java - 如何在 TestNG 中使用 Mockito 模拟 jdbc 连接和 resultSet

android - Retrofit2:尝试将其中包含多个对象的对象作为 Json 发布?

android - Gson会忽略序列化时枚举的自定义@SerializedName值

android - 处理分块传输编码改造 2

android - 禁用 ImageButton

android - 如何在 setCanceledOnTouchOutside 事件取消 DialogFragment 时隐藏屏幕键盘

android - 在 category.HOME Activity 中覆盖主页键长按

java - 为什么mockito 没有注入(inject)正确的响应?

java - 为什么我无法在使用 Maven 的 Junit 测试运行中访问 src/test/resources?