Automatic testing of ApiController

前端 未结 4 1903
悲哀的现实
悲哀的现实 2021-01-23 06:35

I have an ApiController and would like to test it with unit tests including the routing.

An example:

[RoutePrefix(\"prefix\")]
public class          


        
4条回答
  •  被撕碎了的回忆
    2021-01-23 06:54

    1. Create an OWIN StartUp class using Microsoft ASP.NET Web API 2.2 OWIN package:

      public class Startup
      { 
          public void Configuration(IAppBuilder builder)
          {
              var config = new HttpConfiguration();
      
              builder.UseWebApi(config);
      
              config.MapHttpAttributeRoutes();
              config.EnsureInitialized();
          }
      }
      
    2. Use Microsoft ASP.NET Web API 2.2 Self Host package in your tests (used NUnit for example):

      [Test]
      [TestCase(10, 5, 15)]
      [TestCase(1, 2, 3)]
      // add your test cases
      public async Task AdditionTests(int a, int b, int result) 
      {
          // Arrange
          var address = "http://localhost:5050";
      
          using (WebApp.Start(address))
          {
              var client = new HttpClient();
      
              var requestUri = $"{address}/prefix/{a}?id2={b}";
      
              // Act
              var response = await client.GetAsync(requestUri);
      
              // Assert
              Assert.IsTrue(await response.Content.ReadAsAsync() == result);
          }
      }
      

提交回复
热议问题