[英]How do I unit test requests against SSL-only Web Api Controller?
I have a unit test which uses the OWIN TestServer
class to host my Web Api ApiController
classes for testing. 我有一个单元测试,该单元测试使用OWIN
TestServer
类来承载Web Api ApiController
类进行测试。
I first wrote the unit test when the REST API did not have the HTTPS (SSL) requirement baked into the Controller
itself. 当REST API没有将HTTPS(SSL)要求引入
Controller
本身时,我首先编写了单元测试。
My unit test looked something like this: 我的单元测试看起来像这样:
[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);
}
}
Now that I've applied the attribute to enforce HTTPS, my unit test fails. 现在,我已经应用了该属性来实施HTTPS,我的单元测试将失败。
How do I fix my test so that, all things being equal, the test passes again? 如何修正测试,以便在所有条件相同的情况下再次通过测试?
To fix this unit test, you need to change the base address for the TestServer
. 要修复此单元测试,您需要更改
TestServer
的基地址。
Once the server has been created set the BaseAddress
property on the created object to use an "https" address. 创建服务器后,在创建的对象上设置
BaseAddress
属性以使用“ https”地址。 Remember the default BaseAddress
value is http://localhost
. 请记住,默认的
BaseAddress
值为http://localhost
。
In which case, you can use https://localhost
. 在这种情况下,可以使用
https://localhost
。
The changed unit test would look as follows: 更改后的单元测试如下所示:
[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.