本文整理汇总了Java中okhttp3.mockwebserver.MockWebServer.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Java MockWebServer.shutdown方法的具体用法?Java MockWebServer.shutdown怎么用?Java MockWebServer.shutdown使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类okhttp3.mockwebserver.MockWebServer
的用法示例。
在下文中一共展示了MockWebServer.shutdown方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkImageApiResponseFail
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void checkImageApiResponseFail() throws Exception {
MockWebServer mockWebServer = startMockWebServer();
//Success response for the info api
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_info_success_response)));
//Fail response for the image api.
mockWebServer.enqueue(new MockResponse().setResponseCode(500));
openActivity();
//Wait for mock api
Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());
//Check if there are text?
assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
INFO_VIEW);
onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(not(CustomMatchers.hasImage())));
Delay.stopDelay();
mockWebServer.shutdown();
}
示例2: testSetsReadTimeout
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void testSetsReadTimeout() throws Exception {
MockWebServer tempWebServer = new MockWebServer();
tempWebServer.enqueue(
new MockResponse().setBody("test").throttleBody(1, TIMEOUT_TIME_MS, TimeUnit.MILLISECONDS));
tempWebServer.start();
try {
getFetcher().loadData(Priority.HIGH, callback);
} finally {
tempWebServer.shutdown();
// shutdown() called before any enqueue() blocks until it times out.
mockWebServer.enqueue(new MockResponse().setResponseCode(200));
}
verify(callback).onLoadFailed(isA(IOException.class));
}
示例3: checkInfoApiResponseFail
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void checkInfoApiResponseFail() throws Exception {
MockWebServer mockWebServer = startMockWebServer();
//Fail response for the info api.
mockWebServer.enqueue(new MockResponse().setResponseCode(500));
//Success response for the image api.
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_image_success_response)));
openActivity();
//Wait for mock api
Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());
//Check if error occurred?
assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
ERROR_VIEW);
Delay.stopDelay();
mockWebServer.shutdown();
}
示例4: main
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse().setBody("{\"name\": \"Jason\"}"));
server.enqueue(new MockResponse().setBody("<user name=\"Eximel\"/>"));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new QualifiedTypeConverterFactory(
GsonConverterFactory.create(),
SimpleXmlConverterFactory.create()))
.build();
Service service = retrofit.create(Service.class);
User user1 = service.exampleJson().execute().body();
System.out.println("User 1: " + user1.name);
User user2 = service.exampleXml().execute().body();
System.out.println("User 2: " + user2.name);
server.shutdown();
}
示例5: checkInfoNotFoundApiResponse
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void checkInfoNotFoundApiResponse() throws Exception {
MockWebServer mockWebServer = startMockWebServer();
//Success response for the info api
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_info_not_found_success_response)));
//Success response for the image api.
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_image_success_response)));
openActivity();
//Wait for mock api
Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());
//Check if is error?
assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
ERROR_VIEW);
Delay.stopDelay();
mockWebServer.shutdown();
}
示例6: main
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
com.google.gson.Gson gson = new GsonBuilder().create();
MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
.addConverterFactory(
new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory)
.add(Gson.class, gsonConverterFactory)
.add(SimpleXml.class, simpleXmlConverterFactory)
.build())
.addConverterFactory(gsonConverterFactory)
.build();
Service service = retrofit.create(Service.class);
Library library1 = service.exampleMoshi().execute().body();
System.out.println("Library 1: " + library1.name);
Library library2 = service.exampleGson().execute().body();
System.out.println("Library 2: " + library2.name);
Library library3 = service.exampleSimpleXml().execute().body();
System.out.println("Library 3: " + library3.name);
Library library4 = service.exampleDefault().execute().body();
System.out.println("Library 4: " + library4.name);
server.shutdown();
}
示例7: checkInfoFoundApiResponse
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void checkInfoFoundApiResponse() throws Exception {
MockWebServer mockWebServer = startMockWebServer();
//Success response for the info api
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_info_success_response)));
//Success response for the image api.
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
com.kevalpatel2106.smartlens.test.R.raw.wiki_image_success_response)));
openActivity();
//Wait for mock api
Delay.startDelay(TestConfig.DELAY_FOR_REAL_API);
onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());
//Check if there are text?
assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
INFO_VIEW);
onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(CustomMatchers.hasImage()));
Delay.stopDelay();
mockWebServer.shutdown();
}
示例8: main
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
public static void main(String... args) throws IOException, InterruptedException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.enqueue(new MockResponse());
server.start();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ChunkingConverterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build();
Service service = retrofit.create(Service.class);
Repo retrofitRepo = new Repo("square", "retrofit");
service.sendNormal(retrofitRepo).execute();
RecordedRequest normalRequest = server.takeRequest();
System.out.println(
"Normal @Body Transfer-Encoding: " + normalRequest.getHeader("Transfer-Encoding"));
service.sendChunked(retrofitRepo).execute();
RecordedRequest chunkedRequest = server.takeRequest();
System.out.println(
"@Chunked @Body Transfer-Encoding: " + chunkedRequest.getHeader("Transfer-Encoding"));
server.shutdown();
}
示例9: assertCached
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
int expectedResponseCode = responseCode;
server = new MockWebServer();
MockResponse mockResponse = new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setResponseCode(responseCode)
.setBody("ABCDE")
.addHeader("WWW-Authenticate: challenge");
if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
|| responseCode == HttpURLConnection.HTTP_RESET) {
mockResponse.setBody(""); // We forbid bodies for 204 and 205.
}
server.enqueue(mockResponse);
if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
// 408's are a bit of an outlier because we may repeat the request if we encounter this
// response code. In this scenario, there are 2 responses: the initial 408 and then the 200
// because of the retry. We just want to ensure the initial 408 isn't cached.
expectedResponseCode = 200;
server.enqueue(new MockResponse()
.setHeader("Cache-Control", "no-store")
.setBody("FGHIJ"));
}
server.start();
URL url = server.url("/").url();
HttpURLConnection connection = openConnection(url);
assertEquals(expectedResponseCode, connection.getResponseCode());
// Exhaust the content stream.
readAscii(connection);
CacheResponse cached = cache.get(url.toURI(), "GET", null);
if (shouldPut) {
assertNotNull(Integer.toString(responseCode), cached);
} else {
assertNull(Integer.toString(responseCode), cached);
}
server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
示例10: assertCached
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
int expectedResponseCode = responseCode;
server = new MockWebServer();
MockResponse mockResponse = new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setResponseCode(responseCode)
.setBody("ABCDE")
.addHeader("WWW-Authenticate: challenge");
if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
|| responseCode == HttpURLConnection.HTTP_RESET) {
mockResponse.setBody(""); // We forbid bodies for 204 and 205.
}
server.enqueue(mockResponse);
if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
// 408's are a bit of an outlier because we may repeat the request if we encounter this
// response code. In this scenario, there are 2 responses: the initial 408 and then the 200
// because of the retry. We just want to ensure the initial 408 isn't cached.
expectedResponseCode = 200;
server.enqueue(new MockResponse()
.setHeader("Cache-Control", "no-store")
.setBody("FGHIJ"));
}
server.start();
Request request = new Request.Builder()
.url(server.url("/"))
.build();
Response response = client.newCall(request).execute();
assertEquals(expectedResponseCode, response.code());
// Exhaust the content stream.
response.body().string();
Response cached = cache.get(request);
if (shouldPut) {
assertNotNull(Integer.toString(responseCode), cached);
cached.body().close();
} else {
assertNull(Integer.toString(responseCode), cached);
}
server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
示例11: assertCached
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
int expectedResponseCode = responseCode;
server = new MockWebServer();
MockResponse response = new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setResponseCode(responseCode)
.setBody("ABCDE")
.addHeader("WWW-Authenticate: challenge");
if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
response.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
response.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
} else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
|| responseCode == HttpURLConnection.HTTP_RESET) {
response.setBody(""); // We forbid bodies for 204 and 205.
}
server.enqueue(response);
if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
// 408's are a bit of an outlier because we may repeat the request if we encounter this
// response code. In this scenario, there are 2 responses: the initial 408 and then the 200
// because of the retry. We just want to ensure the initial 408 isn't cached.
expectedResponseCode = 200;
server.enqueue(new MockResponse()
.addHeader("Cache-Control", "no-store")
.setBody("FGHIJ"));
}
server.start();
URL url = server.url("/").url();
HttpURLConnection conn = urlFactory.open(url);
assertEquals(expectedResponseCode, conn.getResponseCode());
// exhaust the content stream
readAscii(conn);
Response cached = cache.get(new Request.Builder().url(url).build());
if (shouldPut) {
assertNotNull(Integer.toString(responseCode), cached);
cached.body().close();
} else {
assertNull(Integer.toString(responseCode), cached);
}
server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
示例12: main
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
public static void main(String... args) throws IOException {
// Create a local web server which response with a 404 and JSON body.
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse()
.setResponseCode(404)
.setBody("{\"message\":\"Unable to locate resource\"}"));
// Create our Service instance with a Retrofit pointing at the local web server and Gson.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(GsonConverterFactory.create())
.build();
Service service = retrofit.create(Service.class);
Response<User> response = service.getUser().execute();
// Normally you would check response.isSuccess() here before doing the following, but we know
// this call will always fail. You could also use response.code() to determine whether to
// convert the error body and/or which type to use for conversion.
// Look up a converter for the Error type on the Retrofit instance.
Converter<ResponseBody, Error> errorConverter =
retrofit.responseBodyConverter(Error.class, new Annotation[0]);
// Convert the error body into our Error type.
Error error = errorConverter.convert(response.errorBody());
System.out.println("ERROR: " + error.message);
server.shutdown();
}
示例13: testRequest
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void testRequest() throws IOException {
MockWebServer server = new MockWebServer();
try {
server.enqueue(new MockResponse().setBody("hello, world!").setResponseCode(200));
HttpUrl httpUrl = server.url("/hello");
// TODO: Rule does not currently work when just using the OkHttpClient default constructor
OkHttpClient client = new OkHttpClient.Builder()
.build();
Request request = new Request.Builder()
.url(httpUrl)
.build();
Response response = client.newCall(request).execute();
assertEquals(200, response.code());
List<MockSpan> spans = getTracer().finishedSpans();
assertEquals(2, spans.size());
assertEquals("GET", spans.get(0).operationName());
assertEquals("GET", spans.get(1).operationName());
} finally {
server.shutdown();
server.close();
}
}
示例14: testExternalVolumes
import okhttp3.mockwebserver.MockWebServer; //导入方法依赖的package包/类
@Test
public void testExternalVolumes() throws Exception {
final MockWebServer server = new MockWebServer();
final String mockResponse = "{\"container\": {\"volumes\": [" +
"{\"containerPath\":\"/data/db\",\"mode\":\"RW\",\"external\":" +
"{\"name\":\"mongodb-testvol\",\"provider\":\"dvdi\",\"options\":" +
"{\"dvdi/driver\":\"rexray\"}}}]}}";
try {
server.enqueue(new MockResponse().setBody(mockResponse));
server.start();
Marathon client = MarathonClient.getInstance(server.url("/").toString());
App app = new App();
app.setId("mongo");
app.setCpus(1.0);
app.setMem(256.0);
app.setContainer(new Container());
app.getContainer().setDocker(new Docker());
app.getContainer().getDocker().setImage("mongo");
app.getContainer().setVolumes(new ArrayList<Volume>());
ExternalVolume externalVolume = new ExternalVolume();
externalVolume.setName("mongodb-testvol");
externalVolume.setMode("RW");
externalVolume.setContainerPath("/data/db");
externalVolume.setProvider("dvdi");
externalVolume.setDriver("rexray");
app.getContainer().getVolumes().add(externalVolume);
final App appRes = client.createApp(app);
assertFalse(appRes.getContainer().getVolumes().isEmpty());
ExternalVolume responseVolume = (ExternalVolume) appRes.getContainer().getVolumes().iterator().next();
assertEquals("mongodb-testvol", responseVolume.getExternalVolumeInfo().getName());
RecordedRequest request = server.takeRequest();
assertNotNull(request);
final String requestBody = request.getBody().readUtf8();
assertNotNull(requestBody);
// request to JSON
JsonObject requestPayload = new Gson().fromJson(requestBody, JsonObject.class);
assertNotNull(requestPayload);
JsonObject requestVolume = requestPayload.getAsJsonObject("container").getAsJsonArray("volumes").get(0).getAsJsonObject();
assertNotNull(requestVolume);
assertEquals("RW", requestVolume.get("mode").getAsString());
assertEquals("/data/db", requestVolume.get("containerPath").getAsString());
} finally {
server.shutdown();
}
}