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