【问题标题】:How do I unit test requests against SSL-only Web Api Controller?如何对仅 SSL 的 Web Api 控制器的请求进行单元测试?
【发布时间】:2016-02-17 20:58:02
【问题描述】:

我有一个单元测试,它使用 OWIN TestServer 类来托管我的 Web Api ApiController 类进行测试。

当 REST API 没有将 HTTPS (SSL) 要求嵌入到 Controller 本身时,我首先编写了单元测试。

我的单元测试看起来像这样:

[TestMethod]
[TestCategory("Unit")]
public async Task Test_MyMethod()
{
    using (var server = TestServer.Create<TestStartup>())
    {
        //Arrange
        var jsonBody = new JsonMyRequestObject();
        var request = server.CreateRequest("/api/v1/MyMethod")
            .And(x => x.Method = HttpMethod.Post)
            .And(x => x.Content = new StringContent(JsonConvert.SerializeObject(jsonBody), Encoding.UTF8, "application/json"));

        //Act
        var response = await request.PostAsync();
        var jsonResponse =
            JsonConvert.DeserializeObject<JsonMyResponseObject>(await response.Content.ReadAsStringAsync());

        //Assert
        Assert.IsTrue(response.IsSuccessStatusCode);
    }

}

现在我已应用该属性来强制执行 HTTPS,但我的单元测试失败了。

如何修复我的测试,以便在所有条件相同的情况下再次通过测试?

【问题讨论】:

    标签: c# unit-testing ssl asp.net-web-api2 owin


    【解决方案1】:

    要修复此单元测试,您需要更改TestServer 的基地址。

    创建服务器后,将创建的对象上的BaseAddress 属性设置为使用“https”地址。请记住默认的BaseAddress 值为http://localhost

    在这种情况下,您可以使用https://localhost

    更改后的单元测试如下所示:

    [TestMethod]
    [TestCategory("Unit")]
    public async Task Test_MyMethod()
    {
        using (var server = TestServer.Create<TestStartup>())
        {
            //Arrange
            server.BaseAddress = new Uri("https://localhost");
            var jsonBody = new JsonMyRequestObject();
            var request = server.CreateRequest("/api/v1/MyMethod")
                .And(x => x.Method = HttpMethod.Post)
                .And(x => x.Content = new StringContent(JsonConvert.SerializeObject(jsonBody), Encoding.UTF8, "application/json"));
    
            //Act
            var response = await request.PostAsync();
            var jsonResponse =
                JsonConvert.DeserializeObject<JsonMyResponseObject>(await response.Content.ReadAsStringAsync());
    
            //Assert
            Assert.IsTrue(response.IsSuccessStatusCode);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2023-03-20
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多