【发布时间】:2021-10-25 13:40:29
【问题描述】:
我试图实现的是我的 GCP 功能的单元测试。我想模拟请求参数来测试我的功能我该怎么做?
这是我的 GCP 函数:
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
String name = request.getFirstQueryParameter("name").orElse("world");
try {
JsonElement requestParsed = gson.fromJson(request.getReader(), JsonElement.class);
JsonObject requestJson = null;
if (requestParsed != null && requestParsed.isJsonObject()) {
requestJson = requestParsed.getAsJsonObject();
}
if (requestJson != null && requestJson.has("name")) {
name = requestJson.get("name").getAsString();
}
} catch (JsonParseException e) {
logger.severe("Error parsing JSON: " + e.getMessage());
}
var writer = new PrintWriter(response.getWriter());
writer.printf("Hello %s!", name);
}
这是我的测试:
public class HelloHttpTest {
@Mock private HttpRequest request;
@Mock private HttpResponse response;
private BufferedWriter writerOut;
private StringWriter responseOut;
private static final Gson gson = new Gson();
@BeforeEach
public void beforeTest() throws IOException {
MockitoAnnotations.initMocks(this);
BufferedReader reader = new BufferedReader(new StringReader(""));
when(request.getReader()).thenReturn(reader);
responseOut = new StringWriter();
writerOut = new BufferedWriter(responseOut);
when(response.getWriter()).thenReturn(writerOut);
}
@Test
public void helloHttp_noParamsGet() throws IOException {
new HelloHttp().service(request, response);
writerOut.flush();
Assertions.assertEquals(responseOut.toString(),"Hello world!");
}
}
我想测试这条线name = requestJson.get("name").getAsString(); 是否工作。如何使用 name 参数发出虚假请求,而我的 GCP 会得到它?
【问题讨论】:
-
把name参数作为json请求。
-
你能给我看一下吗?谢谢
标签: java unit-testing google-cloud-platform junit google-cloud-functions