くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

AndroidでRetrofit2をつかってみた

AndroidAPIクライアントライブラリのRetrofit2を使ってみたときの備忘録。

build.gradle
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'

// OkHttpのログを見たいとき
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

// AdapterにRxJavaを使うとき
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' // RxJava2はこっち。RxJava1用もあるので注意
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'

// ConverterにGsonを使うとき
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.google.code.gson:gson:2.8.1'

How To Use

InterfaceでAPIを定義する

public interface ApiClient {
  @POST("login")
  Observable<LoginBean> login(@Query("user") String user, @Query("pass") String pass);
}

InterfaceからAPIクライアントを生成する

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

 ApiClient apiClient = new Retrofit.Builder()
        .client(new OkHttpClient.Builder().addInterceptor(interceptor).build()) // ロガーを追加したOkHttpClientを設定
        .baseUrl("https://sample.com/")
        .addConverterFactory(GsonConverterFactory.create()) // ConverterにGsonを使う
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // CallAdapterにRxJava2を使う
        .build() // ビルダーを作って
        .create(ApiClient.class); // APIクライントを生成

How To Test

RxJava2のテストは非同期のため、通常通りではうまくいかない
テスト用のTestObserverがあるので、それを使ってテストする
※RxJava1ではTestSubscriberだったが、RxJava2ではTestObserverに置き換わった

@RunWith(AndroidJUnit4.class)
public class TestLoginUseCase {
    private static final String TAG = TestLoginUseCase.class.getSimpleName();

    @Test
    public void test_login_success() throws CtiException {
        // Dagger2を使っているので、そこからインスタンスを取得
        AppModule module = new AppModule(getApplication());
        ServerApi serverApi = module.provideServerApi();
        PrefHandler prefHandler = module.providePrefHandler(module.provideContext());
        prefHandler.setCCode("dev_test");
        LoginUseCase loginUseCase = module.provideLoginUseCase(serverApi, prefHandler);

        String uid = "admin001";
        String pwd = "123456";
        // テスト用のObserverを用意
        TestObserver<LoginBean> subscriber = TestObserver.create();
        loginUseCase.login(uid, pwd).subscribe(subscriber);

        subscriber.awaitTerminalEvent();  // CompleteかErrorになるまで待つ
        subscriber.assertComplete()         // Completeかどうかのアサート
                .assertNoErrors();                  // Errorがないかのアサート
        LoginBean loginBean = subscriber.values().get(0); // Completeになった結果を取得
        assertEquals("200", loginBean.getCode());
        assertEquals("success", loginBean.getStatus());
        assertEquals("success", loginBean.getMessage());
        assertEquals("success", loginBean.getExpiration_datetime());
    }

    AppApplication getApplication() {
        return (AppApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
    }
}

参考にしたサイト様