简体   繁体   中英

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:

http://example/Home/Index would be unauthenticated

http://example/Home/Index?token=293029420932422823 would be authenticated

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?

I've seen some things hinting at using Moq but I can't quite join the dots...


NOTE : Please don't suggest answers along the lines of "don't do authentication like that, you should {etc etc etc} instead". The example is intentionally simplified to maintain focus on the main issue here, which is how to develop the unit tests.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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