我正在使用 MVP 架构开发应用程序。我正在尝试使用 MockWebServer 测试我的应用程序的交互器。好吧,我有这个测试:
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, manifest = "src/main/AndroidManifest.xml", packageName = "br.com.simplepass.simplepassnew", sdk = intArrayOf(23))
class LoginInteractorImplTest {
lateinit var mLoginInteractor : LoginInteractor
lateinit var mServer: MockWebServer
@Before
fun setUp(){
mLoginInteractor = LoginInteractorImpl()
mServer = MockWebServer()
mServer.start()
}
@Test
fun loginTest(){
mServer.url("http://192.168.0.10:8080/login")
val testSubscriber = TestSubscriber.create<User>()
mLoginInteractor.login("31991889992", "lala").subscribe(testSubscriber)
testSubscriber.assertNoErrors()
// testSubscriber.assertCompleted()
}
@After
fun tearDown(){
mServer.shutdown()
}
}
但是,当我取消注释 TestSubscriber 上的 assertCompleted 时,我总是得到 assertionError ...我知道 TestSubscriber 有效,因为我在其他测试中使用它。
这是我的 ApiCall:
@GET("login")
fun login() : Observable<User>
我的网络模块:
@Module
class NetModule(val mBaseUrl: String) {
@Provides
@Singleton
fun provideHttpCache(application: Application): Cache {
val cacheSize = 10 * 1024 * 1024
return Cache(application.cacheDir, cacheSize.toLong())
}
@Provides
@Singleton
fun provideOkhttpClient(cache: Cache) : OkHttpClient {
val client = OkHttpClient.Builder()
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
client.addInterceptor(interceptor)
return client.cache(cache).build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(mBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build()
}
}
我的基本 URL(没有后端服务器......可以是任何东西):
<string name="api_base_url">http://192.168.0.12:8080</string>
那么,我错过了什么?这段代码应该可以工作...
欢迎任何帮助!
编辑:
因此,我将代码更改为:
mLoginInteractor = LoginInteractorImpl()
mServer = MockWebServer()
mServer.enqueue(MockResponse()
.setResponseCode(200)
.setBody(Gson().toJson(User(1, "991889992", "Leandro", "123"))))
mServer.start()
val client = OkHttpClient.Builder()
val cacheSize = 10 * 1024 * 1024
client.cache(Cache(application.cacheDir, cacheSize.toLong())).build()
mLoginInteractor.setRetrofit(Retrofit.Builder()
.baseUrl(mServer.url("/"))
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client.cache(Cache(application.cacheDir, cacheSize.toLong())).build())
.build())
和这个:
val testSubscriber = TestSubscriber.create<User>()
mLoginInteractor.login("31991889992", "lala").subscribe(testSubscriber)
testSubscriber.assertNoErrors()
testSubscriber.assertReceivedOnNext(listOf(User(1, "991889992", "Leandro", "123")))
testSubscriber.assertCompleted()
但我仍然收到此错误:
Number of items does not match. Provided: 1 Actual: 0.
Provided values: [User(id=1, phoneNumber=991889992, name=Leandro, password=123)]
Actual values: []