尝试运行单元测试时,出现以下IllegalArgumentException:
java.lang.IllegalArgumentException: in == null
at okio.Okio.source(Okio.java:128)
at okio.Okio.source(Okio.java:124)
at com.example.SearchApiTest.enqueueResponse(SearchApiTest.kt:57)
at com.example.SearchApiTest.enqueueResponse$default(SearchApiTest.kt:54)
at com.example.SearchApiTest.searchLocations(SearchApiTest.kt:48)
错误消息似乎表明该错误发生在行上:
val source = Okio.buffer(Okio.source(inputStream))
这是我下面的单元测试:
@RunWith(JUnit4::class)
class SearchApiTest {
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var api: SearchApi
private lateinit var mockWebServer: MockWebServer
@Before
fun createService() {
mockWebServer = MockWebServer()
api = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(LiveDataCallAdapterFactory())
.build()
.create(SearchApi::class.java)
}
@After
fun stopService() {
mockWebServer.shutdown()
}
@Test
fun searchLocations() {
enqueueResponse("searchLocations.json")
val value = getValue(api.searchLocations("usa"))
val locations = (value as ApiSuccessResponse).body
assertThat(locations.totalResults, `is`(20))
}
private fun enqueueResponse(fileName: String, headers: Map<String, String> = emptyMap()) {
val inputStream = javaClass.classLoader
.getResourceAsStream("api-response/$fileName")
val source = Okio.buffer(Okio.source(inputStream))
val mockResponse = MockResponse()
for ((key, value) in headers) {
mockResponse.addHeader(key, value)
}
mockWebServer.enqueue(
mockResponse
.setBody(source.readString(Charsets.UTF_8))
)
}
}