Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c# - Trying to write a unit Test an azure function through SendGrid that process an email

I have the following azure function that I created locally and using SendGrid email service to send my email.

I'm not sure how to write a unit test that will call a ProcessEmail and pass value to a req. I know this have to be done locally. Any tips will be greatly appreciated.

  public static async Task<IActionResult> ProcessEmail(
               [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
        HttpRequest req, ILogger log) 
     {
        log.SmpLogInformation("Http trigger function to process request");

        var apiKey = ConfigurationManager.AppSettings["Apikey"];
        var requestBody = new StreamReader(req.Body).ReadToEnd();
        var data = JsonConvert.DeserializeObject<EmailContent>(requestBody);

        if (data == null) {
            throw new ArgumentNullException("Data could not be null");
        }

        var client = new SendGridClient(apiKey);

        var message = new SendGridMessage();
        message.AddTo(data.Email);
        message.SetFrom(new EmailAddress("Lisa@aol.=com"));
        message.AddContent("text/html", HttpUtility.HtmlDecode(data.Body));
       
        message.SetSubject(data.Subject);
        log.SmpLogDebug("Email sent through sendGrid");
        await client.SendEmailAsync(message);

        return (ActionResult)new OkObjectResult("EmailSent");
    }

I'm trying to follow this pattern but still having trouble in completing this.

[TestMethod]
public async Task ProcessEmail() {
//Arrange
var request = new HttpRequestMessage();
//...populate as needed for test

var logger = Mock.Of<ILogger>(); //using Moq for example
//...setup expected behavior

//Act
var response = await MyFunction.Run(request, logger);

//Assert
//...assert desired behavior in the response 

}

question from:https://stackoverflow.com/questions/65894286/trying-to-write-a-unit-test-an-azure-function-through-sendgrid-that-process-an-e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...