简体   繁体   中英

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.

I first wrote the unit test when the REST API did not have the HTTPS (SSL) requirement baked into the Controller itself.

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.

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 .

Once the server has been created set the BaseAddress property on the created object to use an "https" address. Remember the default BaseAddress value is http://localhost .

In which case, you can use 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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM