使用TestServer测试ASP.NET Core API

今儿给大家分享下,在ASP.NET Core下使用TestServer进行集成测试,这意味着你可以在没有IIS服务器或任何外部事物的情况下测试完整的Web应用程序。下面给出示例: 

 public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();

            AutoMapperConfig.RegisterMappings();
        }
        [HttpGet]
        [Route("HomeVideo")]
        [ProducesResponseType(typeof(VideoProHomeDataModel), (int)HttpStatusCode.OK)]
        public HttpResponseMessage HomeVideo(int pd)
        {
            if (pd == 0)
                return Error("参数 pd 不能为 0");
            var result = _videoService.HomeVideoList();

            var identityList = new List<string>();
            identityList.AddRange(result.LookBack.Select(x => x.VideoIdentity));
            identityList.AddRange(result.SpeciaList.Select(x => x.VideoIdentity));

            var allVideoPageView = HttpLinkVideoPlay.GetVidepPageViewList(pd, ProjectName, HttpDefaultValue.VideoModuleName, identityList).KeyList.ToDictionary(x => x.CounterKey);

            result.TopAdvList.ForEach(x =>
            {
                x.VideoImg = ReplaceVideoImg(x.VideoImg, VideoMaxImg);
            });

            result.LookBack.ForEach(x =>
            {
                x.VideoImg = ReplaceVideoImg(x.VideoImg, VideoMinImg);
                if (allVideoPageView.ContainsKey(x.VideoIdentity))
                {
                    x.Pageview = allVideoPageView[x.VideoIdentity].KeyCount;
                }
            });
            result.SpeciaList.ForEach(x =>
            {
                x.VideoImg = ReplaceVideoImg(x.VideoImg, VideoMinImg);
                if (allVideoPageView.ContainsKey(x.VideoIdentity))
                {
                    x.Pageview = allVideoPageView[x.VideoIdentity].KeyCount;
                }
            });
            return Success(result);
        }

  

  1. 添加一个新的Test项目
  2. 添加对Web项目的引用
  3. 添加NuGet包: Microsoft.AspNetCore.TestHost
  4. 创建一个测试
public class TestStartup : Startup
    {
        public TestStartup(IConfiguration configuration, IHostingEnvironment env) : base(configuration, env)
        {
        }

        public void ConfigureTestServices(IServiceCollection services)
        {
             // todo:为测试环境配置服务
        }
    }

  

[TestClass]
public class Tests
{
    [TestMethod]
    public async Task TestMethod1()
    {
        var webHostBuilder =
              new WebHostBuilder()
                    .UseEnvironment("Development")
                    .UseStartup<TestStartup>(); 

        using (var server = new TestServer(webHostBuilder))
        using (var client = server.CreateClient())
        {
            string result = await client.GetStringAsync("/api/pro/HomeVideo?pd=2");
             Assert.AreEqual(result.TopAdvList.Count > 0, true);
        }
    }
}

 以上就是ASP.NET Core集成测试的简单介绍。

原文地址:https://www.cnblogs.com/oneweek/p/7798994.html