簡體   English   中英

如何針對僅SSL的Web Api控制器對測試請求進行單元化?

[英]How do I unit test requests against SSL-only Web Api Controller?

我有一個單元測試,該單元測試使用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);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM