单元测试Swagger输出 [英] Unit Test Swagger Output

查看:154
本文介绍了单元测试Swagger输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC WebAPI项目中使用Swagger.该项目已安装Swashbuckle块软件包,并生成Swagger UI和Swagger/docs/v1.我遇到的一个一致的问题是,开发人员将通过不仔细命名其webAPI操作来破坏swagger文件.我想添加一个单元测试,以防止我通过部署后转到Swagger UI网站并看到在swagger UI中显示HTTP 500来发现swagger/docs/v1不可用.有人知道如何编写单元测试来验证Swashbuckle是否可以成功生成swagger文档吗?

I am using Swagger in an ASP.NET MVC WebAPI project. This project has Swashbuckle nugget package installed and generates Swagger UI and Swagger/docs/v1. A consistent problem I'm having is developers will break the swagger file by not carefully naming their webAPI operations. I would like to add a unit test to prevent me from finding out that swagger/docs/v1 isn't available by going to the Swagger UI site after deployment and seeing an HTTP 500 displayed in the swagger UI. Does anybody know how to write a unit test to validate that Swashbuckle can successfully generate the swagger docs?

推荐答案

找到了一种实现我想要的好方法:

Found a great way to do what I want:

[Fact]
public async Task TestSwagger()
{
    var webHostBuilder =
          new WebHostBuilder()
                .UseEnvironment("Test") // You can set the environment you want (development, staging, production)
                .UseStartup<Startup>(); // Startup class of your web app project

    using (var server = new TestServer(webHostBuilder))
    using (var client = server.CreateClient())
    {
        string result = await client.GetStringAsync("/swagger/v1/swagger.json");
        JObject root = JObject.Parse(result);
    }
}

这使用以下nuget包:

This uses the following nuget package:

  • Microsoft.AspNetCore.TestHost

这篇关于单元测试Swagger输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆