如何使用令牌对帖子(web-api)调用进行单元测试?

use*_*003 7 unit-testing web-applications asp.net-web-api dotnet-httpclient asp.net-web-api2

我有一个httppost web api方法.我需要传递一个令牌作为授权头并收集响应.

我正在使用web-api 2.我的post方法返回IHttpActionResult ok(model).

我已经使用POSTMAN rest客户端对web-api进行了测试.

我陷入困境,在那里,我无法编写UNIT-TEST来测试我的API.

另外,我不能将Unit测试项目和web-api项目放在同一个解决方案中吗?我尝试将单元测试项目和web-api项目设置为启动项目.但是单元测试项目只是一个库,因此不起作用.

有人可以指导我这个吗?

gri*_*urd 14

首先,您通常将Unit测试项目和Api项目放在同一解决方案中.但是API项目应该是启动项目.然后,您可以使用visual studio test explorer或其他等效项(fx构建服务器)来运行单元测试.

要测试您的API控制器,我建议您在单元测试中创建一个Owin测试服务器,并使用它来针对您的API执行HTTP请求.

    [TestMethod]
    public async Task ApiTest()
    {
        using (var server = TestServer.Create<Startup>())
        {
            var response = await server
                .CreateRequest("/api/action-to-test")
                .AddHeader("Content-type", "application/json")
                .AddHeader("Authorization", "Bearer <insert token here>")
                .GetAsync();

            // Do what you want to with the response from the api. 
            // You can assert status code for example.

        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,您必须使用依赖注入来注入您的模拟/存根.您必须在Tests项目的启动类中配置依赖项注入.

下面是这也解释了Owin测试服务器,并更详细地启动类的文章.