|
| 1 | +/* |
| 2 | + * Copyright 2021 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package dialogflow.cx; |
| 18 | + |
| 19 | +import static com.google.common.truth.Truth.assertThat; |
| 20 | +import static org.mockito.Mockito.when; |
| 21 | + |
| 22 | +import com.google.cloud.functions.HttpRequest; |
| 23 | +import com.google.cloud.functions.HttpResponse; |
| 24 | +import com.google.gson.Gson; |
| 25 | +import java.io.BufferedReader; |
| 26 | +import java.io.BufferedWriter; |
| 27 | +import java.io.IOException; |
| 28 | +import java.io.StringReader; |
| 29 | +import java.io.StringWriter; |
| 30 | +import org.junit.Before; |
| 31 | +import org.junit.Test; |
| 32 | +import org.mockito.Mock; |
| 33 | +import org.mockito.MockitoAnnotations; |
| 34 | + |
| 35 | +public class ExampleIT { |
| 36 | + |
| 37 | + @Mock private HttpRequest request; |
| 38 | + @Mock private HttpResponse response; |
| 39 | + |
| 40 | + private BufferedWriter writerOut; |
| 41 | + private StringWriter responseOut; |
| 42 | + private static final Gson gson = new Gson(); |
| 43 | + |
| 44 | + @Before |
| 45 | + public void beforeTest() throws IOException { |
| 46 | + MockitoAnnotations.initMocks(this); |
| 47 | + |
| 48 | + // use an empty string as the default request content |
| 49 | + BufferedReader reader = new BufferedReader(new StringReader("")); |
| 50 | + when(request.getReader()).thenReturn(reader); |
| 51 | + |
| 52 | + responseOut = new StringWriter(); |
| 53 | + writerOut = new BufferedWriter(responseOut); |
| 54 | + when(response.getWriter()).thenReturn(writerOut); |
| 55 | + } |
| 56 | + |
| 57 | + @Test |
| 58 | + public void helloHttp_bodyParamsPost() throws IOException, Exception { |
| 59 | + |
| 60 | + String firstHalf = "{\fulfillmentInfo\": {\"tag\": \"Default Welcome Intent\",}"; |
| 61 | + String secondHalf = ",\"text\": \"hi\",\"languageCode\": \"en\",}"; |
| 62 | + |
| 63 | + BufferedReader jsonReader = new BufferedReader(new StringReader(firstHalf + secondHalf)); |
| 64 | + |
| 65 | + when(request.getReader()).thenReturn(jsonReader); |
| 66 | + |
| 67 | + new Example().service(request, response); |
| 68 | + writerOut.flush(); |
| 69 | + |
| 70 | + assertThat(responseOut.toString()).contains("Hello from a Java GCF Webhook"); |
| 71 | + } |
| 72 | +} |
0 commit comments