You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android UI自动化的Espresso框架中调用REST API?

在Espresso测试中调用REST API的Gradle依赖与实现步骤

没错,你需要额外添加HTTP客户端的依赖——Espresso本身只专注于UI交互和断言,并没有内置REST API调用的能力。下面我会一步步告诉你怎么配置和实现:

第一步:添加Gradle依赖

推荐使用Android生态中最常用的两个库:Retrofit(封装性强,适合结构化API调用)或者OkHttp(轻量灵活,适合自定义请求)。你可以根据需求二选一,或者结合使用。

Groovy版本(build.gradle)

dependencies {
    // 基础Espresso测试依赖(如果还没配置的话)
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'

    // 如果你选Retrofit(带Gson解析)
    androidTestImplementation 'com.squareup.retrofit2:retrofit:2.9.0'
    androidTestImplementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    // 如果你选OkHttp单独使用
    androidTestImplementation 'com.squareup.okhttp3:okhttp:4.11.0'
}

Kotlin DSL版本(build.gradle.kts)

dependencies {
    // 基础Espresso测试依赖
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")

    // Retrofit + Gson
    androidTestImplementation("com.squareup.retrofit2:retrofit:2.9.0")
    androidTestImplementation("com.squareup.retrofit2:converter-gson:2.9.0")

    // OkHttp单独使用
    androidTestImplementation("com.squareup.okhttp3:okhttp:4.11.0")
}

添加完依赖后,点击Sync Now同步Gradle即可。

第二步:在Espresso测试中调用API并断言

这里以Retrofit为例,给你一个完整的测试示例:

1. 定义API接口和数据类

先把API的结构映射成Kotlin/Java类:

// API接口定义
interface UserApiService {
    @GET("users/{userId}")
    suspend fun getUserById(@Path("userId") userId: String): Response<User>
}

// 对应API返回的User数据类
data class User(
    val id: String,
    val userName: String,
    val email: String
)

2. 编写Espresso测试用例

在你的AndroidTest目录下创建测试类,结合API调用和UI断言:

@RunWith(AndroidJUnit4::class)
class UserProfileUITest {

    private lateinit var userApiService: UserApiService

    @Before
    fun setupApiClient() {
        // 初始化Retrofit客户端
        val retrofit = Retrofit.Builder()
            .baseUrl("https://your-test-api-domain.com/") // 替换成你的测试API地址
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        userApiService = retrofit.create(UserApiService::class.java)
    }

    @Test
    fun testProfileDisplaysCorrectApiData() {
        // 1. 调用API获取预期数据
        val expectedUser = runBlocking {
            val response = userApiService.getUserById("test_user_001")
            response.body() ?: throw AssertionError("API返回数据为空")
        }

        // 2. 启动要测试的Activity
        val intent = Intent(ApplicationProvider.getApplicationContext(), UserProfileActivity::class.java)
        intent.putExtra("USER_ID", "test_user_001")
        ActivityScenario.launch(intent)

        // 3. 断言UI显示内容与API返回一致
        onView(withId(R.id.tv_user_name))
            .check(matches(withText(expectedUser.userName)))
        onView(withId(R.id.tv_user_email))
            .check(matches(withText(expectedUser.email)))
    }
}

一些实用的注意事项

  • 协程处理:Retrofit的suspend函数需要在协程中调用,测试里用runBlocking可以方便地阻塞等待API响应。
  • API认证:如果你的API需要Token,可以给OkHttp添加拦截器自动注入请求头:
    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor { chain ->
            val authRequest = chain.request().newBuilder()
                .header("Authorization", "Bearer your_test_token")
                .build()
            chain.proceed(authRequest)
        }
        .build()
    // 然后在Retrofit.Builder中添加.client(okHttpClient)
    
  • 测试环境隔离:务必使用测试专用的API环境,不要直接调用生产接口,避免污染数据或触发不必要的业务逻辑。
  • 超时设置:为了避免测试因API响应过慢失败,可以给OkHttp添加超时配置:
    val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()
    

内容的提问来源于stack exchange,提问作者Pinky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:15:03