Issue
I was trying to implement was an unit test for my GCP function. And I want to mock the request param to test my function how do I do it?
This is my GCP function:
@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);
}
And this is my test:
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!");
}
}
I want to test this line name = requestJson.get("name").getAsString();
is working or not. How can I make a fake request with name
params and the my GCP will get it?
Solution
Try the following
BufferedReader reader = new BufferedReader(new StringReader("{\"name\":\"world\"}"));
Answered By - Roman C
Answer Checked By - Mary Flores (JavaFixing Volunteer)