Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide mock data when testing with Espresso

We have a very large Android application with no tests. We're suffering the typical quality/too long manual regression testing cycles problem.

As a server side developer, who is new to Android, I want to introduce developer tests.

I can see how to unit test normal Java code with JUnit.

However, the Activities/Fragments/Adapters are proving more difficult.

I watched the Espresso video from GTAC and was impressed and decided to use that.

Where I'm struggling is how to provide my testcase with mocked data to then confirm the display.

Is this even possible? It seems that Espresso is for black box testing, which limits its use for developers considerably (its target audience) since (usually) black box testing is done by QA.

like image 465
FinalFive Avatar asked May 15 '14 18:05

FinalFive


2 Answers

There is a library called mockwebserver which allows you to mock server responses. Github: https://github.com/square/okhttp/tree/master/mockwebserver

If you are using gradle you can add the following dependency:

 androidTestCompile 'com.squareup.okhttp:mockwebserver:1.3.0'

Some snippets to help:

setup a mock Server

MockWebServer server = new MockWebServer(); 

Add a sample response (will only work the first time the server is called)

server.enqueue(new MockResponse().setBody("Hello World Response"));

Start the server

 server.play();

Get the url of the server to replace the regular url you are using.

  URL baseUrl = server.getUrl("/");

Now, make a request to anything that uses the BaseURL the same way you would call a non mocked web service, the first time you call the service it will return the response from above. The tricky part is that you have the have the exact number of MockResponses queued up as actually requests your app will make. Be careful with debugging/watching your code because the debugger will actually pop one of the responses off if you are stepping through your code.

If you have trouble figuring it out, here is a java web project (works exactly the same in web and not web) I have a few a basic example written in. https://github.com/digitalbuddha/GitPullRank

like image 143
FriendlyMikhail Avatar answered Nov 18 '22 20:11

FriendlyMikhail


I faced the same problem, and couldn't find any fremowork that fits perfectly what I needed. But Wiremock was the one that got close.

I use it to record the api answers, and/or in reproduction mode, and when on record mode, if the request was already recorded, it wont record again. Although its not fully supported on android (yet), I run it as standalone on my machine, and then run the app or espresso tests. You can also manually edit or add the requests or answers.

You will find a lot of more details here

like image 22
juhlila Avatar answered Nov 18 '22 19:11

juhlila