Sample code for unit testing api controllers

后端 未结 4 869
遥遥无期
遥遥无期 2021-02-04 03:44

Is there an sample code that shows unit testing a controller that inherits from the api controller? I am trying to unit test a POST but it is failing. I believe I need to set up

4条回答
  •  感情败类
    2021-02-04 04:22

    Sample code for unit testing API controller with async fundtion in C#

    1. Prepare test Models:

              using System;
              namespace TestAPI.Models
              {
                  public class TestResult
                  {
                      public DateTime Date { get; set; }
                      public bool Success { get; set; }
                      public string Message { get; set; }
                  }      
              }
      
    2. Prepare test controller

              using TestAPI.Models;
              using System;
              using System.Net;
              using System.Threading.Tasks;
              using System.Web.Http;
              using System.Web.Http.Description;
      
              namespace TestAPI.Controllers
              {   
                  public class TestController : ApiController
                  {       
                      public TestController()
                      {           
                      }
      
                      [HttpPost]
                      [ResponseType(typeof(TestResult))]
                      [Route("api/test/start")]
                      public async Task StartTest()
                      {                                
                          DateTime startTime = DateTime.Now;
                          var testProcessor = new TestAsync();
                          await testProcessor.StartTestAsync();                                     
      
                          HttpStatusCode statusCode = HttpStatusCode.OK;
                          return Content(statusCode, new TestResult
                          {
                              Date = DateTime.Now,
                              Success = true,
                              Message = "test"
                          }); 
                      }       
      
                  }
              }
      
    3. unit test async controller with result check from response

              using Microsoft.VisualStudio.TestTools.UnitTesting;
              using TestAPI.Controllers;
              using TestAPI.Models;
              using System.Web.Http;
              using System.Threading.Tasks;
              using System.Net;
              using System.Web.Script.Serialization;
      
              namespace Unit.Tests.Controllers
              {
                  /// 
                  /// Summary description for ControllerTest
                  /// 
                  [TestClass]
                  public class ControllerTest
                  {
                      private TestController _testController;       
                      [TestInitialize]
                      public void estAPI_Initializer()
                      {
                          _testController = new TestController();
                          var configuration = new HttpConfiguration();
                          System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage();
                          request.Headers.Add("Authorization", "Bearer 1232141241");
                          request.Headers.Add("ContentType", "application/json");
                          _testController.Request = request;
                          _testController.Configuration = configuration;            
                      }
      
                      [TestCategory("Unit test")]
                      [TestMethod]
                      public async Task API_Async_Controller_Test()
                      {
                          IHttpActionResult asyncResponse = await _testController.StartTest();
                          var cToken = new System.Threading.CancellationToken(true);           
                          var rResult = asyncResponse.ExecuteAsync(cToken);                      
                          Assert.IsNotNull(rResult);
                          Assert.IsNotNull(rResult.Result);
                          Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK);
                          Assert.IsNotNull(rResult.Result.Content);
                          var rContent = rResult.Result.Content;
      
                          string data = await rContent.ReadAsStringAsync();
                          Assert.IsNotNull(data);
                          JavaScriptSerializer JSserializer = new JavaScriptSerializer();
                          var finalResult = JSserializer.Deserialize(data);
      
                          Assert.IsNotNull(finalResult);
                          Assert.IsTrue(finalResult.Success);
                      }        
                  }
              }
      

提交回复
热议问题