c# - 如何针对仅支持 SSL 的 Web Api Controller 对请求进行单元测试?

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

我有一个单元测试,它使用 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,我的单元测试失败了。

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

最佳答案

要修复此单元测试,您需要更改 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);
    }

}

关于c# - 如何针对仅支持 SSL 的 Web Api Controller 对请求进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33740838/

相关文章:

C# 处理数据上下文

c# - 如何利用 EF 和 LINQ 添加过滤器并动态指定表、列、过滤器和排序依据

regex - Jasmine Expect toMatch 和括号

ssl - 将网站移至 https 现在搜索控制台不会在新的 https 搜索控制台属性中为页面编制索引

ssl - Telegram Bot API Webhooks 自签名证书问题

c# - 递增和递减运算符 C#

c# - 图像重映射算法

Spring Boot 测试失败, 'No bean named ' webHandler'可用'

java - EasyMock 和 Annotations 以及 2 个相同类型的依赖项

c - 使用wolfSSL时get_peer_certificate错误