我首先运行一个模拟登录测试,它返回状态代码 400,然后是第二个使用真实服务调用登录的测试。测试如下:
@Test
public void mock() throws IOException, InterruptedException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(400));
server.start();
NetworkServiceHelper.init(String.valueOf(server.url("/"))); // Change retrofit baseUrl to localhost
loginWithoutWaiting(username, password);
server.shutdown();
}
@Test
public void real() {
NetworkServiceHelper.init(NetworkServiceHelper.DEFAULT_URL); // Change retrofit baseUrl to a real url
loginWithoutWaiting(username, password);
}
真正的服务不会被调用。EditText 错误消息说
无法验证:无法连接到 localhost/127.0.0.1:50162
这是初始化 Retrofit 实例的 NetworkServiceHelper.init() 函数:
public static synchronized void init(String serverUrl) {
// Override the GSON date format.
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
// We want to make the network calls asynchronous, so use createWithScheduler()
RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
// Finally, build the Retrofit client.
retrofit = new Retrofit.Builder()
.baseUrl(serverUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(rxAdapter)
.client(buildClient())
.build();
}