toadflakz
toadflakz

Reputation: 7944

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?

Upvotes: 2

Views: 1422

Answers (1)

toadflakz
toadflakz

Reputation: 7944

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);
    }

}

Upvotes: 6

Related Questions