sendgrid-go icon indicating copy to clipboard operation
sendgrid-go copied to clipboard

Create interface for testability

Open amclay opened this issue 4 years ago • 2 comments

Issue Summary

It would be nice to have an interface available for mocking or a provided fake client that allows clients to utilize the library without sending real emails.

Steps to Reproduce

N/A

Code Snippet

ex:

type SendGrid interface {
  Send(email *mail.SGMailV3) (*rest.Response, error)
}

Then consumers can create their own mocks using https://github.com/vektra/mockery or https://github.com/maxbrunsfeld/counterfeiter

amclay avatar Oct 29 '20 15:10 amclay

Relates to https://github.com/sendgrid/sendgrid-go/pull/420

This issue has been added to our internal backlog to be prioritized. Pull requests and +1s on the issue summary will help it move up the backlog.

childish-sambino avatar Oct 30 '20 17:10 childish-sambino

Hello, I created a SendGrid interface in #420 for test integration

package main

import (
	"fmt"
	"os"

	"github.com/sendgrid/sendgrid-go"
	"github.com/sendgrid/sendgrid-go/helpers/mail"
	"github.com/sendgrid/sendgrid-go/helpers/mock"
)

func main() {

	// start mocks server
	mock.StartTestServer()

	// add mock value
	mock.Add(&mock.Mock{
		StatusCode: 400,
		Body:       `{ "errors":[{ "message":"Example error.", "field":"example field" }] }`,
	})


	simpleSendMail() // Response with mock data

	// stop mocks server
	mock.StopTestServer()

}

func simpleSendMail() {
	from := mail.NewEmail("Example User", "[email protected]")
	subject := "Sending with Twilio SendGrid is Fun"
	to := mail.NewEmail("Example User", "[email protected]")
	plainTextContent := "and easy to do anywhere, even with Go"
	htmlContent := "<strong>and easy to do anywhere, even with Go</strong>"
	message := mail.NewSingleEmail(from, subject, to, plainTextContent, htmlContent)
	
	// create mock client
	client := sendgrid.NewSendClientMock(os.Getenv("SENDGRID_API_KEY"))

	response, err := client.Send(message)
	if err != nil {
		fmt.Println("Simple Sengird Error: ")
		fmt.Println(err)
		fmt.Println("________________________________")
		fmt.Println()
	} else {
		fmt.Println("Simple Sengird Response: ")
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
		fmt.Println("________________________________")
		fmt.Println()
	}
}

ncostamagna avatar Nov 19 '20 05:11 ncostamagna