toa*_*akz 1 c# ssl unit-testing owin asp.net-web-api2
我有一个单元测试,它使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我已应用该属性来强制执行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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
889 次 |
| 最近记录: |