简体   繁体   中英

How to mock params request unit test google cloud function?

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?

Try the following

BufferedReader reader = new BufferedReader(new StringReader("{\"name\":\"world\"}"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM