Arc*_*nes 5 android unit-testing mockito retrofit2
例如,我有一个改造界面,例如:
interface SampleService {
fun getSomething(@body someBody: SomeBody)
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个使用这个接口的类,例如:
class UserRequester(val service: SampleService) {
fun doGetSomething(someValue: String) {
val response = service.getSomething(SomeBody(someValue))
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试这个类,但不知道如何模拟它。
我正在尝试以下操作:
val mockSampleService = mock()
val userRequester = UserRequester(mockSampleService)
val requestBody = SomeBody(someString))
when(mockSampleService.getSomething(requestBody)).return(myExpectedValue)
....
Run Code Online (Sandbox Code Playgroud)
我的问题是,由于我在函数内部创建了请求对象,因此我无法使模拟 when().thenReturn() 工作,因为我在技术上传递了两个不同的对象。
我应该如何测试这个?提前致谢。
模拟问题(UserRequester)
您无法模拟该mockSampleService方法,因为您的类正在创建该对象并且与您在测试中创建的对象SomeBody不同。SomeBody
现在你有2个选择:
Mockito.any(),这样您基本上就可以说,无论您的方法将用作参数,您都将返回模拟的行为someString使用给定返回值的工厂,SomeObject如下所示:
// the factory
class SomeObjectFactory{
fun createSomeObject(someString: String): SomeObject {
return SomeObject(someString)
}
}
//the class
class UserRequester(
val service: SampleService, val factory: SomeObjectFactory
) {
fun doGetSomething(someValue: String) {
val response = service.getSomething(factory.createSomeObject(someValue))
// ...
}
}
//the test
class MyTest{
@Test
fun myTestMethod(){
val mockSampleService = mock()
val factory = mock()
val someBody = mock()
val userRequester = UserRequester(mockSampleService, factory)
`when`(factory.createSomeObject(someString)).thenReturn(someBody)
`when`(mockSampleService.getSomething(someBody)).thenReturn(myExpectedValue)
//rest of the code
}
}
第二种方法是最干净的方法。
测试 Retrofit 调用 (SampleService)
我不会unit test打电话给改造。
当您处理框架、API、数据库时,共享首选项总是integration tests比unit tests.
通过这种方式,您实际上是在测试您的代码是否可以与外界一起工作。
我建议您使用MockWebServer测试 Retrofit 调用(它是来自Square开发 OkHttp 和 Retrofit 的同一家公司的库)。
阅读本文可能也会有所帮助。
| 归档时间: |
|
| 查看次数: |
4063 次 |
| 最近记录: |