MockWebServer example
suggest changeWhen activities, fragments, and other UI need background processing, a MockWebServer can run locally on the device and give the UI a closed, testable environment.
https://github.com/square/okhttp/tree/master/mockwebserver
First step is including the gradle dependency:
testCompile 'com.squareup.okhttp3:mockwebserver:(insert latest version)'
Now steps for running and using the mock server are:
- create mock server object
- start it at specific address and port (usually localhost:portnumber)
- enqueue responses for specific requests
- start the test
The MockWebServer GitHub page explains the basic steps. The rule below starts and stops a server around a test. apply does not call super.apply, so the UiThreadTestRule behavior is not used. The dependency line above still has a version placeholder.
/**
*JUnit rule that starts and stops a mock web server for test runner
*/
public class MockServerRule extends UiThreadTestRule {
private MockWebServer mServer;
public static final int MOCK_WEBSERVER_PORT = 8000;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
startServer();
try {
base.evaluate();
} finally {
stopServer();
}
}
};
}
/**
* Returns the started web server instance
*
* @return mock server
*/
public MockWebServer server() {
return mServer;
}
public void startServer() throws IOException {
mServer = new MockWebServer();
try {
mServer.start(MOCK_WEBSERVER_PORT);
} catch (IOException e) {
throw new IllegalStateException("mock server start issue", e);
}
}
public void stopServer() {
try {
mServer.shutdown();
} catch (IOException e) {
Timber.e(e, "mock server shutdown error");
}
}
}
Assume the same activity as in the previous example. In this case, pushing the button fetches from the network, for example https://someapi.com/name
This would return some text string which would be concatenated in the snackbar text e.g. NAME + text you typed in.
/**
* Testing of the snackbar activity with networking.
**/
@RunWith(AndroidJUnit4.class)
@LargeTest
public class SnackbarActivityTest{
//espresso rule which tells which activity to start
@Rule
public final ActivityTestRule<SnackbarActivity> mActivityRule =
new ActivityTestRule<>(SnackbarActivity.class, true, false);
//start mock web server
@Rule
public final MockServerRule mMockServerRule = new MockServerRule();
@After
public void tearDown() throws Exception {
//same as previous example
}
@Before
public void setUp() throws Exception {
//same as previous example
// Point the application at the mock server, for example
MyAppConfig.setEndpointURL("http://localhost:8000");
}
/**
*Test methods should always start with "testXYZ" and it is a good idea to
*name them after the intent what you want to test
**/
@Test
public void testSnackbarIsShown() {
//setup mockweb server
mMockServerRule.server().setDispatcher(getDispatcher());
mActivityRule.launchActivity(null);
//check is our text entry displayed and enter some text to it
String textToType="new snackbar text";
onView(withId(R.id.textEntry)).check(matches(isDisplayed()));
//we check is our snackbar showing text from mock webserver plus the one we typed
onView(withId(R.id.textEntry)).perform(typeText("JazzJackTheRabbit" + textToType));
//click the button to show the snackbar
onView(withId(R.id.shownSnackbarBtn)).perform(click());
//assert that a view with snackbar_id with text which we typed and is displayed
onView(allOf(withId(android.support.design.R.id.snackbar_text),
withText(textToType))) .check(matches(isDisplayed()));
}
/**
*creates a mock web server dispatcher with prerecorded requests and responses
**/
private Dispatcher getDispatcher() {
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getPath().equals("/name")){
return new MockResponse().setResponseCode(200)
.setBody("JazzJackTheRabbit");
}
throw new IllegalStateException("no mock set up for " + request.getPath());
}
};
return dispatcher;
}
}
setUp and tearDown use JUnit @Before and @After. The assertion checks only textToType. The field is filled with "JazzJackTheRabbit" + textToType, while the comment describes the server body plus the typed text.
A builder can chain responses for a screen:
return newDispatcherBuilder()
.withSerializedJSONBody("/authenticate", Mocks.getAuthenticationResponse())
.withSerializedJSONBody("/getUserInfo", Mocks.getUserInfo())
.withSerializedJSONBody("/checkNotBot", Mocks.checkNotBot());