Java MockWebServer 的心得

Retrofit2 + OKHttp3 真是神器

很久之前寫了剛開始寫 Java ,整理了一下自己在 spring 上使用 Retrofit2 與 okHttp3 的使用 心得

最近又發現 OKHttp3 plugin MockWebServer。在做第三方 API 測試的時候,真的滿方便的。


MockWebServer

使用 Retrofit 建立一個 FacebookService,
建立方式, 參考之前的心得


public interface FacebookService {
    @GET("{userId}?fields=id, name")
    Call getFbUser(@Path("userId") String userId, @Query("access_token") String token);
}

測試


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockWebServerDemo.class)
@WebAppConfiguration
public class MockWebServerTest {

    private MockWebServer mockWebServer;
    private FacebookService facebookService;
    private ObjectMapper objectMapper;

    @Before
    public void setUp() {
        // Jackson objectMapper
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper
            .registerModule(new JodaModule())
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

        // mockWebServer
        mockWebServer = new MockWebServer();

        // 注入到 Retrofit
        Retrofit mockRetrofit = new Retrofit.Builder()
            .baseUrl(mockWebServer.url(""))  // 給個空的 url
            .addConverterFactory(JacksonConverterFactory.create(objectMapper))
            .build();

        facebookService = mockRetrofit.create(FacebookService.class);
    }

    @After
    public void tearDown() throws IOException {
        // 記得 shutdown
        mockWebServer.shutdown();
    }

    @Test
    public void testFacebookService() throws IOException {
        final Integer testUserId = 123;
        final String testName = "fake-facebook-name";

        // 假裝 Facebook API Response 200
        mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody("{" +
                "  \"id\": \"" + testUserId + "\"," +
                "  \"name\": \"" + testName + "\"" +
                "}")
        );

        // act
        FacebookUserInfoDTO fbUser =
            facebookService.getFbUser(String.valueOf(testUserId), testName)
            .execute()
            .body();

        Assert.assertEquals(testUserId, fbUser.getId());
        Assert.assertEquals(testName, fbUser.getName());
    }

沒有留言:

張貼留言