.NET by Patrik

How to Properly Use Assert.Contains for Substring Checks in .NET

When writing unit tests in .NET using Assert.Contains, it's easy to accidentally check for exact matches when you only want to check if a string is part of another.

Here’s a common mistake:

Assert.Contains("TestCookie=TestValue", cookieStrings);

This fails if cookieStrings contains items like "TestCookie=TestValue; Path=/; HttpOnly" — because "TestCookie=TestValue" is not an exact match to any item.

How to Fix It

Use the lambda version of Assert.Contains to check for a substring match:

Assert.Contains(cookieStrings, c => c.Contains("TestCookie=TestValue"));

This makes sure that at least one string in the collection includes "TestCookie=TestValue" somewhere inside it.

Example Use Case

In a test where you're adding a cookie to an HttpClient, you might write:

Assert.Contains(
    httpClient.DefaultRequestHeaders.GetValues("Cookie"),
    c => c.Contains("TestCookie=TestValue")
);

Summary

  • Assert.Contains(item, collection) checks for exact matches.
  • Use Assert.Contains(collection, predicate) to check for substring matches.
  • Ideal for validating headers, cookies, or complex strings in collections.
testing
assert
dotnet
httpclient
xunit

Comments