Learning Android Development

Android Mock Server for UnitTest

Make unit test for network fetching easier

Photo by Jonathan on Unsplash

Almost every app we build today will fetch something from the server. How nice if we can unit test the logic with some mock payload, or even better mock server that can emulate various service conditions?

The good news is, Square who provided OkHttp libraries, also have MockWebServer for their OkHttp.

Setting it up

Library dependencies

To use it, obviously, you need to be already using OkHttp (that also applies if you use Retrofit). Then you just need to add the Mock Web Server Library through in the app’s build.gradle file.

implementation 'com.squareup.okhttp3:okhttp:4.8.0'
testImplementation 'com.squareup.okhttp3:mockwebserver:4.3.1'

Instantiating the Mock Server

Below is how you just instantiate var server = MockWebserver(). And when you are starting, just…

--

--