junit 如何测试Kotlin/suspend功能?

pvabu6sv  于 2022-11-24  发布在  Kotlin
关注(0)|答案(1)|浏览(168)

嘿伙计们我试过这个

@ExtendWith(MockKExtension::class)
internal class RecipeServiceImplTest {
@MockK
lateinit var apollo: ApolloClientConfig

@InjectMockKs
lateinit var recipeService: RecipeServiceImpl

@Test
fun getDietaryRestrictionsTest() {
    val requestConfig = RequestConfig(
        Optional.presentIfNotNull("en"),
        Optional.presentIfNotNull(1)
    )
    val stringList: List<String> = listOf<String>("ALCOHOL_FREE", "GLUTEN_FREE", "LACTOSE_FREE")
    val search: GetDietaryRestrictionQuery.Search = GetDietaryRestrictionQuery.Search(stringList)
    val data: GetDietaryRestrictionQuery.Data = GetDietaryRestrictionQuery.Data(search)

    coEvery {
        apollo.buildApolloClient().query(GetDietaryRestrictionQuery(requestConfig, 999))
            .execute().data
    } returns data
    
    var result: Any

    runBlocking {
        result = recipeService.getDietaryRestrictions("en", 1)!!
    }

    coVerify(exactly = 1) {
        apollo.buildApolloClient().query(GetDietaryRestrictionQuery(requestConfig, 999))
            .execute().data
    };
    assertEquals(data, result)

}

但说“我不知道”
无法将类强制转换为类com.apollographql.apollo3.api.ApolloResponse(加载程序“应用程序”的未命名模块中包含此类)
我的职责是

override suspend fun getDietaryRestrictions(locale: String?, supportedApiVersion: Int?): GetDietaryRestrictionQuery.Data? {
    return this.apolloClientConfig.buildApolloClient()
        .query(GetDietaryRestrictionQuery(initRequestConfig(locale, supportedApiVersion),999))
        .execute().data
}

这是我的配置

@Configuration
class ApolloClientConfig(private val appProperties: AppProperties) {
    @Bean
    fun buildApolloClient(): ApolloClient {
        return ApolloClient.Builder()
            .serverUrl(appProperties.foodfitteryCoreDevUri)
            .build()
    }

}

k2fxgqgv

k2fxgqgv1#

在我看来,coEvery块中方法调用的参数不一定与实际调用参数匹配。调用没有被模拟,因此出现错误。
尝试使用any()而不是coEverycoVerify中的实际值:

coEvery {
    apollo.buildApolloClient().query(any())
        .execute().data
} returns data

相关问题