简体   繁体   English

如何模拟参数请求单元测试谷歌云 function?

[英]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?我试图实施的是我的 GCP function 的单元测试。我想模拟请求参数来测试我的 function 我该怎么做?

This is my GCP function:这是我的 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();我想测试这一行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?我怎样才能用name参数发出虚假请求,而我的 GCP 会得到它?

Try the following尝试以下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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