Search code examples
c#unit-testingnunitresponse-headers

Why is cache-control header value backwards when I check against them?


The headers are being appended like so.

context.Response.Headers.Append("Cache-Control", "max-age=0,no-cache,no-store");

When I do an equality check (below) for a unit test, it is failing because the 3 items are in reverse order ("no-store,no-cache,max-age=0") when I read it back.

Assert.IsTrue(resp.Result.Headers.GetValues("Cache-Control")
    .First()
    .Equals("max-age=0,no-cache,no-store"));

Any idea why that could possibly be? Or, a better way to do a comparison for my unit test?


Solution

  • The Headers property of class HttpResponse is a NameValueCollection. The documentation for NameValueCollection says:

    This class can be used for headers, query strings and form data.

    Each element is a key/value pair.

    Collections of this type do not preserve the ordering of element, and no particular ordering is guaranteed when enumerating the collection.

    So, you cannot rely on a particular ordering.

    If you really want to do a check if the set header values are there, you could perform a string Contains operation instead.

    One could argue, however, that you would in fact be unit testing the .NET framework (and not your code) with this. In other words, you might want to reconsider writing such a test in the first place.