当前位置:  开发笔记 > 编程语言 > 正文

如何在C#单元测试中将测试Cookie添加到请求中

如何解决《如何在C#单元测试中将测试Cookie添加到请求中》经验,为你挑选了1个好方法。



1> Nkosi..:

这是一个示例单元测试,其中在请求上设置了cookie。

使用NSubstitute框架模拟http上下文,然后设置请求cookie属性。将模拟的http上下文应用于控制器上下文以模拟请求。

[TestClass]
public class MyControllerTests {
    [TestMethod]
    public void Request_Cookies_Should_Not_Be_Null() {
        //Arrange
        var cookies = new HttpCookieCollection();
        cookies.Add(new HttpCookie("usercookie"));

        var mockHttpContext = Substitute.For();
        mockHttpContext.Request.Cookies.Returns(cookies);

        var sut = new MyController();
        sut.ControllerContext = new ControllerContext {
            Controller = sut,
            HttpContext = mockHttpContext
        };

        //Act
        var result = sut.Dashboard() as ViewResult;

        //Assert
        Assert.IsNotNull(result);
    }

    public class MyController : Controller {
        public ActionResult Dashboard() {
            if (Request.Cookies["usercookie"] == null) {
                return RedirectToAction("Index");
            }
            return View();
        }
    }
}

更新:

这是使用手动创建的模拟HttpContext进行的测试的更新版本。

[TestClass]
public class MyControllerTests {
    [TestMethod]
    public void Request_Cookies_Should_Not_Be_Null() {
        //Arrange
        var cookies = new HttpCookieCollection();
        cookies.Add(new HttpCookie("usercookie"));

        var mockHttpContext = new MockHttpContext(cookies);

        var sut = new MyController();
        sut.ControllerContext = new ControllerContext {
            Controller = sut,
            HttpContext = mockHttpContext
        };

        //Act
        var result = sut.Dashboard() as ViewResult;

        //Assert
        Assert.IsNotNull(result);
    }

    public class MyController : Controller {
        public ActionResult Dashboard() {
            if (Request.Cookies["usercookie"] == null) {
                return RedirectToAction("Index");
            }
            return View();
        }
    }


    private class MockHttpContext : HttpContextBase {
        private readonly MockRequest request;
        public MockHttpContext(HttpCookieCollection cookies) {
            this.request = new MockRequest(cookies);
        }

        public override HttpRequestBase Request {
            get {
                return request;
            }
        }

        public class MockRequest : HttpRequestBase {
            private readonly HttpCookieCollection cookies;
            public MockRequest(HttpCookieCollection cookies) {
                this.cookies = cookies;
            }

            public override HttpCookieCollection Cookies {
                get {
                    return cookies;
                }
            }
        }

    }
}

推荐阅读
oDavid_仔o_880
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有