【发布时间】:2020-09-11 18:02:23
【问题描述】:
我正在为使用改造服务的 AuthenticationDataSource 类编写单元测试,所以我使用 MockWebServer 来模拟响应,这是我运行测试时的输出:
java.lang.IllegalStateException: This job has not completed yet
这是我的测试类 AuthenticationDataSourceTest:
@ExperimentalCoroutinesApi
class AuthenticationDataSourceTest {
private val mockWebServer: MockWebServer = MockWebServer()
private lateinit var apiService: ApiService
private lateinit var SUT: AuthenticationDataSource
@Before
fun setUp() {
mockWebServer.start()
apiService =
Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory.invoke())
.build()
.create(ApiService::class.java)
val mockApolloClient = mockk<ApolloClient>()
SUT = AuthenticationDataSource(apiService, mockApolloClient)
}
@After
fun tearDown() {
mockWebServer.shutdown()
}
@Test
fun retrieveAccessToken_returnsAccessToken() = runBlockingTest {
// Given
val response = MockResponse()
.setResponseCode(HttpURLConnection.HTTP_OK)
.setBody(FileUtils.readTestResourceFile("access_token_success.json"))
mockWebServer.enqueue(response)
// When
val accessToken = SUT.getAccessToken("", "", "")
// Then
assertThat(accessToken).isNotNull()
}
}
这是我的 AuthenticationDataSource 类:
class AuthenticationDataSource @Inject constructor(
private val retrofitService: ApiService,
private val apolloClient: ApolloClient
) {
suspend fun getAccessToken(
clientId: String,
clientSecret: String,
code: String
): Result<Token> {
return try {
val tokenModel = retrofitService.getAccessToken(
clientId = clientId,
clientSecret = clientSecret,
redirectUri = Constant.REDIRECT_URI,
grantType = "authorization_code",
code = code
)
Result.Success(tokenModel)
} catch (throwable: Throwable) {
Timber.e(throwable)
Result.Error(throwable)
}
}
}
最后是我的 ApiService:
interface ApiService {
@POST("/v2/oauth/token")
suspend fun getAccessToken(
@Query("client_id") clientId: String,
@Query("client_secret") clientSecret: String,
@Query("redirect_uri") redirectUri: String,
@Query("grant_type") grantType: String,
@Query("code") code: String
): Token
}
任何帮助都非常感谢。
【问题讨论】:
-
尝试将此添加到您的测试类中:
@get:Rule val instantExecutorRule = InstantTaskExecutorRule() -
添加规则并没有解决问题。
标签: android unit-testing kotlin retrofit2 kotlin-coroutines