简体   繁体   English

C#-对WebApi控制器进行单元测试

[英]C# - Unit testing a WebApi controller

I am used to test Web controllers in Java in which a real request is being sent to the controller even under a unit test. 我习惯于在Java中测试Web控制器,即使在单元测试中,也向该控制器发送了真正的请求。

When it comes to C# the doc I am seeing like here or here it seems to check the call workflow to the controller methods but not an entire http message workflow. 关于C#,我在这里这里看到的文档似乎是检查控制器方法的调用工作流,而不是整个HTTP消息工作流。

In particular, say i have the following controller: 特别是说我有以下控制器:

public class SessionController : ApiController
{
    [HttpDelete]
    [ResponseType(typeof(IHttpActionResult))]
    [Route("api/v1/sessions/{session-id}")]
    [ActionName("stop_session")]
    [ValidateModel]
    public IHttpActionResult StopSession([FromUri(Name = "session-id")] Guid sessionId)
    {
        Console.WriteLine($"Stopping session {sessionId}");

        SessionRepository.Instance.Remove(sessionId);

        return Ok();
    }
}

If i create the following unit test: 如果我创建以下单元测试:

    [TestMethod]
    public void TestStopSession()
    {
        SessionController controller = new SessionController()
        {
            Request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("http://localhost:9000/api/v1/zada")
            }
        };
        controller.Configuration = new HttpConfiguration();

        var res = controller.StopSession(new Guid());

        Assert.IsInstanceOfType(res, typeof(OkResult));
    }

As you can see, in test I am putting a different URL and even a different method and still the unit test passes successfully. 如您所见,在测试中,我放置了一个不同的URL甚至一个不同的方法,但是单元测试仍然成功通过了。

What is the way to unit test the entire HTTP workflow? 对整个HTTP工作流程进行单元测试的方法是什么?

I this case your are testing the unit TestStopSession from the SessionController , and not any routing, validation etc. I think that's OK for an unit test, as you need to test one unit at once. 在这种情况下,您正在从SessionController测试单元TestStopSession ,而不是任何路由,验证等。我认为对于单元测试来说还可以,因为您需要一次测试一个单元。

You're calling the method TestStopSession, so there isn't even a routing take place here. 您正在调用方法TestStopSession,所以这里甚至没有路由。

What is the way to unit test the entire HTTP workflow? 对整个HTTP工作流程进行单元测试的方法是什么?

You need an integration or system test then. 您需要进行集成或系统测试。 You could spin up a HTTP listener and then do the raw request. 您可以启动HTTP侦听器,然后执行原始请求。

But keep in mind, don't write to many integration / system tests. 但是请记住,不要写很多集成/系统测试。 Be sure to know the test pyramid 一定要知道测试金字塔

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM