1

我首先运行一个模拟登录测试,它返回状态代码 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();
}
4

1 回答 1

0

确保您像以下方式一样懒惰地调用活动

@Rule
    public ActivityTestRule<EmergencyMainActivity> mActivityTestRule =
            new ActivityTestRule<>(EmergencyMainActivity.class, true, false);

然后在设置服务器网络调用后调用活动。

于 2017-04-01T14:39:34.367 回答