[英]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.