如何在c#中编写Web挂钩的单元测试用例?

时间:2020-01-15 06:51:14

标签: asp.net unit-testing nunit httprequest webhooks

我有一个网页,该网页接收Web挂钩请求,并且我想为此Web挂钩编写单元测试用例(NUnit框架)。我想在单元测试用例中模拟Web挂钩请求(发布请求),并将 request标头和正文作为 Json数据传递到接收请求的网页。 / p>

网页名称

/webhook/receiveWebHook.aspx

请求标头

Content-Type: application/json
messageType: TestInsertNotification

请求正文(Json数据)

{ 
   "Alias":"Test",
   "TransactionID":"123"
}

网页中的代码:

protected void Page_Load(object sender, EventArgs e)
{
      if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
      {
           object notification = null;
           string message = string.Empty;

           Int32 pID = InsertHTTPRequest(HttpContext.Current.Request); //Generate id in DB

           if (pID > 0 && this.Request.ContentType == "application/json")
           {
                StreamReader sr = new StreamReader(this.Request.InputStream, this.Request.ContentEncoding);
                message = sr.ReadToEnd();
                TextReader content = new StreamReader(new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(message)));
                JToken json = JToken.Load(new JsonTextReader(content));
                notification = new JsonSerializer().Deserialize(new JTokenReader(json), this.GetTypeOfMessage(HttpContext.Current.Request.Headers("MessageType")));   
           }
            if (notification != null)
            {
                 if (notification is InsertNotification)
                 {
                      InsertNotification insertNotification = notification as InsertNotification;
                      DbInsertMethod(pID, message, insertNotification);
                 }
            }
      }
}

有人可以帮助在C#中实现Webhooks的单元测试吗? 另外,请提出如何通过带有标题和正文(包含Json数据)的单元测试方法传递HTTP Post请求的建议?

P.S。:当前,我正在使用Postman测试此Webhook的功能。

1 个答案:

答案 0 :(得分:0)

尝试使用 RestSharp 库。对于您的情况,它看起来像这样:

[TestFixture]
public class TestWebApp
{
    [Test]
    public void TestRequest()
    {
        IRestClient client = new RestClient($"{BaseUrl}/webhook/receiveWebHook.aspx");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/json");
        request.AddHeader("messageType", "TestInsertNotification");
        JObject jObjectbody = new JObject();
        jObjectbody.Add("Alias", "Test");
        jObjectbody.Add("TransactionID", "123");
        request.AddParameter("application/json", jObjectbody, ParameterType.RequestBody);
        var response = client.Execute(request);
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}
相关问题