android服务器接口测试,Android单元测试:网络接口测试

本文介绍了在Android开发中如何进行服务器接口测试,包括使用Retrofit+OkHttp+RxJava2进行网络请求,通过LoggingInterceptor查看返回数据,以及如何模拟数据。文中详细讲解了如何使用Interceptor模拟响应数据和MockWebServer进行更复杂的模拟测试,帮助开发者解决在测试接口时遇到的问题。
摘要由CSDN通过智能技术生成

在平日的开发中,我们用后台写好给我们接口去获取数据。虽然我们有一些请求接口的工具,可以快速的拿到返回数据。但是在一些异常情况的处理上就不太方便了。我列出以下几个痛点:

快速的查看返回数据与数据的处理。(一般我们都是将写好的代码跑到手机上,点击到对应页面的对应按钮)

异常信息的返回与处理。比如一个接口返回一个列表数据,如果列表为空呢?(找后台给我们模拟数据)网速不好呢?(不知道怎么搞…)网络异常呢?(关闭网络)

后台有部分接口没有写好,你就只能等他了。

不知道上面的这三点有没有戳到你的痛处。如果扎心了,那么老铁你就有必要掌握今天的内容。

1.请求接口

我们就使用网络请求三件套(retrofit + okhttp + rxjava2)来举例。

首先添加一下依赖,同时记得加网络权限。

//RxJava

compile 'io.reactivex.rxjava2:rxjava:2.1.7'

//RxAndroid

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

//okhttp

compile "com.squareup.okhttp3:okhttp:3.9.1"

//Retrofit

compile ("com.squareup.retrofit2:retrofit:2.3.0"){

exclude module: 'okhttp'

}

compile ("com.squareup.retrofit2:adapter-rxjava2:2.3.0"){

exclude module: 'rxjava'

}

compile "com.squareup.retrofit2:converter-gson:2.3.0"

测试接口:

public interface GithubApi {

String BASE_URL = "https://api.github.com/";

@GET("users/{username}")

Observable getUser(@Path("username") String username);

}

Retrofit的初始化,我们使用LoggingInterceptor来打印返回数据。

public class GithubService {

private static Retrofit retrofit = new Retrofit.Builder()

.baseUrl(GithubApi.BASE_URL)

.client(getOkHttpClient())

.addConverterFactory(GsonConverterFactory.create())

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

.build();

public static GithubApi createGithubService() {

return retrofit.create(GithubApi.class);

}

private static OkHttpClient getOkHttpClient(){

return new OkHttpClient.Builder()

.addInterceptor(new LoggingInterceptor())

.build();

}

}

测试代码:

@RunWith(RobolectricTestRunner.class)

@Config(constants = BuildConfig.class, sdk = 23)

public class ResponseTest {

@Before

public void setUp() {

ShadowLog.stream = System.out;

initRxJava2();

}

private void initRxJava2() {

RxJavaPlugins.reset();

RxJavaPlugins.setIoSchedulerHandler(new Function() {

@Override

public Scheduler apply(Scheduler scheduler) throws Exception {

return Schedulers.trampoline

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值