3

I would like to test my Rest services build under Retrofit2. I don't want to mock all responses individually, but I would like to mock the entire web server. I found that it's possible with MockServer. But I am not able to work with it.

My Retrofit2 base URL is given by my build type. I tried for instance to create a new build type, for example "staging" like so:

    staging {
        buildConfigField "String", "APP_BASE_URL", "\"http://test.com\""
    }

and added in the gradle config as well

testBuildType "staging"

But my tests aren't working anymore, everything turn red in Intellij. Dependencies aren't found.

Basically what I want to do is that for each test, I want a mock web server with a specific URL. This url will be used by my Retrofit2 interface Base URL, and I want the mockwebserver to response to them with specific JSON file response.

For example:

@Before
override public fun setUp() {
    super.setUp()
    server = MockWebServer()
    server.url("http://test.com")
}

@Test
fun forbiddenLogin() {
    server.enqueue(MockResponse()
            .setResponseCode(403)
            .setBody("{\"message\": \"Forbidden access!\"}")
    )
    server.start()

   //HOW TO CALL AND TESTS MY SERVICES HERE?
}

For information my Retrofit2 service uses RxJava Observable

@POST("/rest/login")
@FormUrlEncoded
fun login(
        @Field("login") login: String,
        @Field("password") password: String
): Observable<ApiWrapper<UserDTO>>
Maurice
  • 2,129
  • 2
  • 25
  • 33
  • Yes yes, I totally forgot this question... I'am going to post a solution. – Maurice Jan 13 '19 at 17:57
  • 1
    Actually I don't have a solution with the build.gradle. What I did was to use an intermediate singleton class, with the purpose of managing and hold server URI information. By doing that, I was able to change every setting in my test. To sum: My retrofit services are now getting server url from the utility class, and by doing that, I can mock my server api. – Maurice Jan 13 '19 at 18:04
  • So you would be calling up a server just that you would be pointing it to the QA server is it? Or do you use local json files? – Rat-a-tat-a-tat Ratatouille Jan 14 '19 at 12:32
  • Yes, I'm setting the test server to this url "http://test.com" and in my app, it's this url that is used as the APP_BASE_URL for Retrofit services. – Maurice Jan 14 '19 at 16:16

0 Answers0