我正在运行模拟Web服务器来测试REST API调用,当活动启动并启动模拟Web服务器并执行API调用时,我使用OKHTTP v-3.10.0和Retrofit 2.3.0拒绝连接>
ActivityTest代码:
@Rule
public ActivityTestRule<STBUpgradeActivity> mActivityRule = new ActivityTestRule<>(STBUpgradeActivity.class, false, false);
private MockWebServer server;
@Before
public void setUp() throws Exception {
super.setUp();
server = new MockWebServer();
server.start();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
String serverUrl = server.url("/").toString();
EnvConfig.WEB_API_SIT = serverUrl;
}
@Test
public void testPageContentIsShown() throws Exception {
String fileName = "stb_upgrade_page_content_200.json";
server.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(RestServiceTestHelper.getStringFromFile(getInstrumentation().getContext(), fileName)));
Intent intent = new Intent();
mActivityRule.launchActivity(intent);
onView(withId(R.id.button_upgrade)).check(matches(isDisplayed()));
onView(withText("New residential subscribers and standard install only. If Sports is a part of your package")).check(matches(isDisplayed()));
}
======== RestAPI客户端
private Retrofit getClient() {
retrofit = new Retrofit.Builder()
.baseUrl(WEB_API_HOST)
.addConverterFactory(GsonConverterFactory.create())
.client(getHttpClient())
.build();
return retrofit;
}
答案 0 :(得分:1)
将设置代码更改为
@Before
public void setUp() throws Exception {
super.setUp();
server = new MockWebServer();
server.start(8080);
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}
将Retroft Base URL设置为
private Retrofit getClient() {
retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/")
.addConverterFactory(GsonConverterFactory.create())
.client(getHttpClient())
.build();
return retrofit;
}