We don't want to call the real SendGrid API, so we'll mock the api() method that calls it. But we do want to verify what we sent to the API, so we'll use a Captor to see the Request that was passed into our mocked api()
*For each argument passed in call the send() method * and check the that actual status code equals the expected*Capture the Request that we send to the SendGridAPI* and validate the API was called correctly only when the contents were valid */@ParameterizedTest(name ="{index} => ''{0}'' - ''{1}''")@MethodSource("payloadProvider")voidvalidates_requests_and_return_with_code_or_call_api(String message,HttpStatus expectedStatus,String sender,String from,String to,String subject,String body,Map<String, String> custom) throws IOException {// Mock the APIlenient().when(sendGridClient.api(any(Request.class))).thenReturn(newResponse(HttpStatus.OK.value(),"{}",null));// create an input SendgridRequest based on the parameterized values passed in and set propertiesvar mailer =newSendgridMailer(sendGridClient);mailer.apiKeyValue=this.apiKeyValue;mailer.host=this.host;mailer.apiVersion=this.apiVersion;mailer.sdkVersion=this.sdkVersion;// call SendgridMailer::send()var response =mailer.send(SendgridRequest.builder().senderName(sender).toAddress(to).fromAddress(from).subject(subject).content(body).customArgs(custom).build());// verify the expected stats codeassertThat(response.getStatusCode()).isEqualTo(expectedStatus.value());// if the status code is OK, then we should have caled the APIif (expectedStatus ==HttpStatus.OK) {verify(sendGridClient).api(apiRequestCaptor.capture());Request request =apiRequestCaptor.getValue();assertThat(request.getMethod()).isEqualTo(Method.POST);assertThat(request.getBaseUri()).isNotNull();assertThat(request.getEndpoint()).isEqualTo(String.format("/%s/mail/send",this.apiVersion));assertThat(request.getHeaders().getOrDefault("Authorization","")).isEqualTo("Bearer "+ apiKeyValue); } else {// If the request fails validation we should have returned early and NOT called the APIverifyNoInteractions(sendGridClient); }}