简体   繁体   中英

How to unit test for turning off request validation?

I'm new at this TDD thing but making a serious effort, so I'm hoping to get some feedback here.

I created a little web service to minify JavaScript, and everything was nice, with all my tests passing. Then I noticed a bug: if I tried to minify alert('<script>'); , it would throw a HttpRequestValidationException .

So that's easy enough to fix. I'll just add [AllowHtml] to my controller. But what would be a good way to unit test that this doesn't happen in the future?

The following was my first thought:

[TestMethod]
public void Minify_DoesntChokeOnHtml()
{
    try
    {
        using (var controller = ServiceLocator.Current.GetInstance<MinifyController>())
        {
            return controller.Minify("alert('<script></script>');");
        }
    }
    catch (HttpRequestValidationException)
    {
        Assert.Fail("Request validation prevented HTML from existing inside the JavaScript.");
    }
}

However, this doesn't work since I am just getting a controller instance and running methods on it, instead of firing up the whole ASP.NET pipeline.

What would be a good unit test for this? Maybe reflector on the controller method to see if the [AllowHtml] attribute is present? That seems very structural, and unlikely to survive a refactoring; something functional might make more sense. Any ideas?

You have only two options:

First

Write integration test that hosts MVC in-proc or runs using browser (using Watin for instance) that will cover you scenario.

Second

Write unit test that will check that method is marked with needed attribute.

I would go with the first option.

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