简体   繁体   English

单元测试取决于请求的URL参数的控制器属性(ASP.NET MVC)

[英]Unit test a controller attribute which depends on the requested URL parameters (ASP.NET MVC)

I basically have a controller base class which handles authentication by validating a token in the url, eg: 我基本上有一个控制器基类,它通过验证url中的令牌来处理身份验证,例如:

http://example/Home/Index would be unauthenticated http:// example / Home / Index将未经身份验证

http://example/Home/Index?token=293029420932422823 would be authenticated http:// example / Home / Index?token = 293029420932422823将通过身份验证

I want to write unit tests for this but not sure how to go about it. 我想为此编写单元测试,但不确定如何去做。 I have: 我有:

    [TestMethod]
    public void NonsecureConnection()
    {
        var controller = new EONSecureController();
        Assert.IsTrue(string.IsNullOrEmpty(controller.EONToken));
        Assert.IsTrue(controller.tokenMode == EONSecureController.EONTokenModeEnum.None);
    }

Easy enough. 很简单。 Testing secure connections is where I'm stuck. 测试安全连接是我遇到的困难。

    [TestMethod]
    public void SecureConnection()
    {
        var controller = new EONSecureController();
        // What to put here?
        Assert.IsTrue(!string.IsNullOrEmpty(controller.EONToken));
        Assert.IsTrue(controller.tokenMode==EONSecureController.EONTokenModeEnum.Client);
    }

I've tried various approaches like: 我尝试了各种方法,例如:

controller.RequestContext.RouteData.Values[Config.RawTokenName] = "12312342123";
controller.Request = new System.Web.HttpRequest("", "http://localhost/example", "token=2342342");
controller.Request.RawUrl = "http://localhost/example?token=234234234234234";

None of which work for various reasons. 由于各种原因,它们都不起作用。 Is there a "correct" way to handle testing a controller that relies on the specific URL being requested? 是否有“正确”的方式来处理依赖于所请求的特定URL的控制器测试?

I've seen some things hinting at using Moq but I can't quite join the dots... 我已经看到一些暗示要使用Moq的东西,但我还不能完全理解...


NOTE : Please don't suggest answers along the lines of "don't do authentication like that, you should {etc etc etc} instead". 注意 :请不要按照“不要那样做身份验证,而应该{etc etc etc}来”建议答案。 The example is intentionally simplified to maintain focus on the main issue here, which is how to develop the unit tests. 有意简化了该示例,以重点关注此处的主要问题,即如何开发单元测试。

单独测试属性-不能与控制器一起测试。

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

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