简体   繁体   English

使用xUnit和.Net Core MVC控制器为CORS创建单元测试

[英]Creating a unit test for CORS with xUnit and .Net Core MVC controller

I want to write a unit test to ensure CORS is on and that a particular WebApi method can only be called from a client that reports to be from a certain domain. 我想编写一个单元测试以确保CORS处于打开状态,并且只能从报告来自某个域的客户端调用特定的WebApi方法。

I think I'm running into a common gotcha that's described here, whereby it's not seen as a true cross domain request... 我想我遇到了这里描述的常见陷阱,因此它不被视为真正的跨域请求...

CORS Gotchas CORS陷阱

The type of unit test would look something like this... 单元测试的类型看起来像这样...

    [Fact]
    public async Task CheckCors()
    {
        var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("http://clientdomain.co.uk/");
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.GetAsync(new Uri($"http://apidomain.co.uk/api/testcors", UriKind.Absolute));

        // Should be forbidden to call the api
        response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
    }

I may have misunderstood things, but can anyone put me right? 我可能对事情有误解,但有人能说对吗?

First of this isn't a unit test because you are making a call out to some external resource. 首先,这不是单元测试,因为您正在呼唤一些外部资源。 Unit tests should have any external dependencies mocked/faked out. 单元测试应该模拟/伪造任何外部依赖项。 This is really an integration test. 这确实是一个集成测试。

Also this isn't really testing your code to configure cors, this is testing that cors actually works. 同样,这并不是真正测试您的代码以配置cors,而是测试cors确实有效。

That being said, I tried writing a unit test for CORS and came up with this. 话虽这么说,我试图为CORS编写单元测试并提出了这个想法。 Given that I have class that configures CORS 鉴于我有配置CORS的课程

public static class CorsConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["CorsClientUrl"], "*", "*")
        {
            SupportsCredentials = true
        };

        config.EnableCors(cors);
    }
}

Where my AppSettings["CorsClientUrl"] has a value of " https://www.google.com " 我的AppSettings["CorsClientUrl"]的值为“ https://www.google.com

So then I want to test that cors is configured after this is called. 因此,我想在调用此功能后测试是否配置了cors。 All my unit test derive from SpecificationBase so that I have a little more BDD style syntax when I write my tests 我所有的单元测试都源自SpecificationBase因此在编写测试时,我有更多的BDD样式语法

[TestFixture]
public abstract class SpecificationBase
{
    [SetUp]
    public void SetUp()
    {
        Given();
        When();
    }

    protected virtual void Given()
    {
    }

    protected virtual void When()
    {
    }
}

public class ThenAttribute : TestAttribute
{
}

And the ultimate unit tests look like this 最终的单元测试如下所示

    public class WhenConfiguringCors : SpecificationBase
    {
        private HttpConfiguration _httpConfiguration;
        private CorsPolicy _corsPolicy;

        protected override void Given()
        {
            _httpConfiguration = new HttpConfiguration();
        }

        protected override void When()
        {
            CorsConfig.Register(_httpConfiguration);

            var corsConfig = _httpConfiguration.Properties["MS_CorsPolicyProviderFactoryKey"] as AttributeBasedPolicyProviderFactory;

            _corsPolicy =
                corsConfig.DefaultPolicyProvider.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None)
                    .Result;
        }

        [Then]
        public void ShouldSetOrigin()
        {
            Assert.That(
                _corsPolicy.Origins.Contains("https://www.google.com"), Is.True);
        }

        [Then]
        public void ShouldSupportCredentials()
        {
            Assert.That(
                _corsPolicy.SupportsCredentials, Is.True);
        }
    }

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

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