Created
September 22, 2017 14:50
-
-
Save frankkienl/374326a003c82b3fe54bd56adf30a293 to your computer and use it in GitHub Desktop.
Retrofit bug, exception on http201 with empty body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package nl.frankkie.retrofitbug; | |
import org.junit.Rule; | |
import org.junit.Test; | |
import okhttp3.ResponseBody; | |
import okhttp3.mockwebserver.MockResponse; | |
import okhttp3.mockwebserver.MockWebServer; | |
import retrofit2.Call; | |
import retrofit2.Callback; | |
import retrofit2.Response; | |
import retrofit2.Retrofit; | |
import retrofit2.converter.gson.GsonConverterFactory; | |
import retrofit2.http.GET; | |
import retrofit2.http.POST; | |
import static junit.framework.Assert.assertEquals; | |
import static junit.framework.Assert.assertTrue; | |
import static junit.framework.Assert.fail; | |
/** | |
* Created by frankb on 22/09/2017. | |
*/ | |
public class RetrofitBug { | |
@Rule | |
public final MockWebServer server = new MockWebServer(); | |
interface MyRestService { | |
@GET("/two_zero_four") | |
Call<MyEmptyResponseBody> giveMe204NoContent(); | |
@POST("/two_zero_one") | |
Call<MyEmptyResponseBody> giveMe201CreatedWithoutContent(); | |
} | |
public class MyEmptyResponseBody { | |
//this class is intentionally empty | |
} | |
@Test | |
public void test() throws Exception { | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl(server.url("/")) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.build(); | |
MyRestService restService = retrofit.create(MyRestService.class); | |
MockResponse mockResponse204 = new MockResponse(); | |
mockResponse204.setResponseCode(204); | |
server.enqueue(mockResponse204); | |
MockResponse mockResponse201 = new MockResponse(); | |
mockResponse201.setResponseCode(201); | |
mockResponse201.setHeader("Location", "/two_zero_one/randomId"); | |
server.enqueue(mockResponse201); | |
Call<MyEmptyResponseBody> call204 = restService.giveMe204NoContent(); | |
try { | |
Response<MyEmptyResponseBody> response204 = call204.execute(); | |
assertEquals(204, response204.code()); | |
assertTrue(response204.isSuccessful()); | |
} catch (Throwable t) { | |
fail(); | |
} | |
Call<MyEmptyResponseBody> call201 = restService.giveMe201CreatedWithoutContent(); | |
try { | |
Response<MyEmptyResponseBody> response201 = call201.execute(); | |
assertEquals(201, response201.code()); | |
assertTrue(response201.isSuccessful()); | |
} catch (Throwable t) { | |
fail(); | |
//This is the bug. | |
//201 can have an empty body, just like 204 does. | |
//But at 204, it generates an Exception | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment