Jon
Jon

Reputation: 1499

Using okhttp mock webserver in production

I've been using okhttp's mock web server (https://github.com/square/okhttp/tree/master/mockwebserver) in testing for quite a bit now and it works really well. From reading the documentation and browsing Google, it seems the library is really targeted for testing.

My question though is whether there is any reason why I couldn't use this in production code? I have an android app that I am working on that requires the need for a mock web server. I've integrated it and it is working fine but I am concerned whether there is something completely wrong with what I am doing.

Also, are there any security risks that I should be aware of when using mock web server in production?

Thanks!

Upvotes: 3

Views: 1996

Answers (1)

Jon Adams
Jon Adams

Reputation: 25147

The MockWebServer returns "mock" (in other words, "not real") data. If you used the class in production, you would have to either continue providing fake data to it, or make real HTTP calls through some separate library or tool and stuff its responses into the MockWebServer. And then, what would be the point? Why not just let OkHttp make the calls directly as it was designed?

My guess is you might be misunderstanding the relationship between OkHttp3 and MockWebServer.

  • OkHttp3 - HTTP client that makes HTTP requests over any HTTP stack (by default, uses the supplied Android device HTTP network; wi-fi, cell, etc.)
  • MockWebServer - only used in tests to supply hard-coded (not real) HTTP responses to an OkHttp HTTP client so that a live network connection is not needed during the tests, or to consistently simulate various network connection issues such as dropped connections, invalid HTTP responses, server errors, etc.

You should only be using OkHttp3 in your application code.

In your tests only, you have MockWebServer to fake responses (or intercept if you configure it that way) to test out your application's calls to OkHttp3. When you go to production, none of the MockWebServer code should ever be referenced or called (since you put it all in the test/androidTest source code directories, right?) and the OkHttp3 code would make real HTTP calls over the internet since MockWebServer won't be there to intercept them anymore.

Basically, if you have anything in your build.gradle other than testCompile 'com.squareup.okhttp3:mockwebserver:x.x.x' and/or androidTestCompile 'com.squareup.okhttp3:mockwebserver:x.x.x' than you're doing it wrong. The main, real, production application has no need for a mock web server since it will be making real calls over the internet to a real web server.

Upvotes: 5

Related Questions