【问题标题】:Unit testing Retrofit calls when service is injected with Dagger 2使用 Dagger 2 注入服务时的单元测试 Retrofit 调用
【发布时间】:2018-10-14 18:28:23
【问题描述】:

我使用 Dagger 2 在 Android 应用程序中提供我的所有课程。我想对构造函数中具有改造服务的存储库类进行单元测试。

class MainRepository(private val service: ImageService) {

fun download(username: String, liveData: MutableLiveData<ImageDownloadResult>) {
    service.downloadImage(username).enqueue(object : Callback<ImageResponse> {
        override fun onFailure(call: Call<ImageResponse>, t: Throwable) {
            liveData.value = DownloadFailed(t)
        }

        override fun onResponse(call: Call<ImageResponse>, response: Response<ImageResponse>) {
            if (response.isSuccessful) {
                response.body()?.let {
                    liveData.value = DownloadSuccessful(it.image)
                }
            } else {
                liveData.value = DownloadFailed(
                    when (response.code()) {
                        401 -> Unauthorized()
                        403 -> Forbidden()
                        404 -> NotFound()
                        in 500..599 -> InternalServerError()
                        else -> General()
                    }
                )
            }
        }
    })
}

}

网络模块类以这种方式提供服务:

@Provides
@Singleton
fun provideImageService(gson: Gson, okHttpClient: OkHttpClient): ImageService {
    return Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .baseUrl(mBaseUrl)
        .client(okHttpClient)
        .build()
        .create(ImageService::class.java)
}

我正在尝试使用 Mockito 来模拟类,但我在 download 方法中得到 NullPointerException。

public class MainRepositoryTest {

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@InjectMocks
ImageService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testImageDownload() {
    MutableLiveData<ImageDownloadResult> liveData = new MutableLiveData<>();
    Response<ImageResponse> response = null;
    try {
        response = service.downloadImage("test").execute();
        assertEquals(response.code(), 200);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

请教我如何将服务注入测试,以便我可以在那里调用 Http 调用。谢谢!

【问题讨论】:

    标签: android unit-testing mockito retrofit2


    【解决方案1】:

    我认为您在这里混淆了一些内容。在测试中,您似乎在测试服务,而不是存储库。服务需要被模拟才能真正返回一些东西而不是 null。

    让我们从测试设置开始。你必须声明模拟和你正在测试的东西

    public class MainRepositoryTest {
    
      @Rule
      public MockitoRule mockitoRule = MockitoJUnit.rule();
      @Mock
      ImageService service;
      @InjectMocks
      MainRepository repository;
    
       //...
     }
    

    存储库是您将在此处实际测试的内容。实际上,您只需获得一个注入了服务模拟的存储库实例。但是,此模拟将在每次方法调用时返回 null。

    所以现在,您需要为要测试的每个案例进行设置。假设你想测试一个成功的响应:

    @Test
    public void testSuccess (){
        when(service.downloadImage("test")).theReturn(<successful response>);
    
         repository.download("test", <mutable live data>);
    
         // Now assert something about the live data
    }
    

    您必须模拟服务以在使用预期参数调用时返回成功的响应。我不确定如何在这里使用实时数据,因为我从未使用过它。我实际上认为改造已经支持这一点,您不必手动转换它。

    至于 dagger,您使用依赖注入真是太好了。但是,在测试中,您通常不会使用 dagger 注入依赖项。在这里使用 mockito 注释就足够了。

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 2017-05-20
      • 2017-11-19
      • 1970-01-01
      • 2015-07-11
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多