简体   繁体   English

如何在 C# 中对 HTTP 处理程序进行单元测试

[英]How to Unit Test HTTP Handlers in C#

I want to unit Test my HTTP Handlers.我想对我的 HTTP 处理程序进行单元测试。 I am Using XUnit framework for unit testing, My Sample Handler Code is我正在使用 XUnit 框架进行单元测试,我的示例处理程序代码是

 public class MyHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
            var data = context.Request.InputStream;
            //Here logic read the context.Request.InputStream
            //All the data will be posted to this Stream
            //Calling of business logic layer Methods
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

I am new to Unit testing and I just want to know What are the possible test cases for testing my HandleS Since the return type of handlers is Void so I am confuse how can I write the Test for Handlers...我是单元测试的新手,我只想知道测试我的 HandleS 的可能测试用例是什么,因为处理程序的返回类型是 Void,所以我很困惑如何编写处理程序测试...

Note : I know HttpContextBase can called using an HttpContextWrapper, I am not asking this I am just asking What are the possible test cases for HttpHandlers注意:我知道可以使用 HttpContextWrapper 调用 HttpContextBase,我不是在问这个,我只是在问 HttpHandlers 的可能测试用例是什么

Testing void methods is an interesting topic.测试 void 方法是一个有趣的话题。 The main way I would go about it is to mock up an HTTP Context, and pass it in as a parameter.我要做的主要方法是模拟一个 HTTP 上下文,并将其作为参数传递。 Then, you should be asserting on the things you are setting that HTTP context to do within your method.然后,您应该断言您正在设置 HTTP 上下文以在您的方法中执行的操作。 For example Assert.Equal("text/plain", myHttpContext.Response.ContentType);例如Assert.Equal("text/plain", myHttpContext.Response.ContentType); However, you need to ensure that you are creating a unit test.但是,您需要确保您正在创建单元测试。 It says you have business logic after this step.它说你在这一步之后有业务逻辑。 Have you inverted your dependencies?你有没有反转你的依赖关系? (Passed them as parameters into the method). (将它们作为参数传递给方法)。 Are you able to mock things out appropriately?你能恰当地模拟事情吗? Make sure the method isn't doing an actual HTTP call (if it is a unit test).确保该方法没有执行实际的 HTTP 调用(如果它是单元测试)。 In general, I recommend less void methods with side affects but in legacy it can't be avoided.一般而言,我建议减少具有副作用的 void 方法,但在传统中它无法避免。 To address your initial question, test cases are going to be anything you logically expect.为了解决您最初的问题,测试用例将是您逻辑上期望的任何内容。 Did I set my route correctly?我是否正确设置了路线? Am I expecting the content to be text?我希望内容是文本吗? Is my payload accurate?我的有效载荷准确吗? Anything you change is a potential test, but ensure you are testing to acceptance criteria.您更改的任何内容都是潜在的测试,但请确保您正在按照验收标准进行测试。 Its okay to have multiple assertions in a test if its one logical assert.如果测试中只有一个逻辑断言,则可以在测试中使用多个断言。

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

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