1
我第一次運行模擬登錄測試,返回狀態代碼400,然後是使用真實服務調用登錄的第二個測試。測試如下:在Android上模仿mockwebserver後無法測試真實服務器的調用?
@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
下面是初始化改造實例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();
}