やりたいこと
・APIにGETリクエストを送るプログラムのテストを書く
・API参照箇所をMockにする
以下記事を参考にさせていただきました
Mockito 3 + JUnit 5 で基本的なモック化とテストをするサンプルコード
https://qiita.com/niwasawa/items/f8798c981b4d08ecfa55
参照APIの構築
テスト用に参照用のAPIを構築する
参考 https://spring.pleiades.io/guides/gs/rest-service/
2つのクラスを作ります
実行するクラスとリクエストを送るクラスを作成する
実行クラス
App.java
public class App {
public String send_request(int user_id) throws MalformedURLException, IOException {
return request.send(user_id);
}
}
リクエスト送付クラス
Request.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Request {
public String send(int user_id) throws MalformedURLException, IOException {
HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:8080/greeting/" + user_id).openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
return out.toString();
}
}
テストクラス
Request.javaをモックに差し替えレスポンスの文字列を定義します
Apptest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import java.io.IOException;
import java.net.MalformedURLException;
public class AppTest {
@InjectMocks
private App kusatest = new App();
@Mock
private Request request = new Request();
public void 正常ケース() throws MalformedURLException, IOException {
String output_expect = "{\"id\":\"2\",\"content\":\"Hello, World!\"}";
doReturn(output_expect).when(request).send(2);
assertEquals(output_expect, kusatest.send_request(2));
}
@Test
public void ユーザーがいない_404() throws MalformedURLException, IOException {
doThrow(IOException.class).when(request).send(10);
Assertions.assertThrows(IOException.class, () -> {
kusatest.send_request(10);
});
}
}
build.gradle(抜粋)
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2'
testImplementation 'org.mockito:mockito-core:3.6.0'
implementation 'com.google.guava:guava:30.0-jre'
testImplementation group: 'org.junit.platform', name: 'junit-platform-launcher', version: '1.8.2'
}
これでテストコード実行時にはAPIに疎通できなくても、モックで定義したレスポンス文字列を受け取り、後続の処理を検証します。