Lesson 13 of 93 · 5 min read · Updated
String Assertions in xUnit: StartsWith, Contains, Matches and Explicit StringComparison
On this page
Text output has a contract like any other result: a prefix, a set of words, a format, and rules about case and culture. xUnit has string assertions for each part of that contract. This lesson tests a URL slug generator with StartsWith, Contains, Matches and explicit StringComparison, and shows the most common mistake with text: leaving the comparison rule unstated.
Technical Requirements
- .NET 11 SDK
- xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)
The Code Under Test: A Slug Generator
SlugGenerator.Create turns a product name into a URL-friendly slug such as urun/kirmizi-urun-5 (urun means "product"). It maps Turkish letters to ASCII, lowercases everything with the invariant culture, and collapses spaces and symbols into single dashes.
M02.XUnitBasics/SlugGenerator.cs
Prefix, Suffix and Substrings
M02.XUnitBasics.Tests/StringAssertionTests.cs
Why not Assert.Equal("urun/mekanik-klavye", slug)? You can, and for a short output it is often the clearest choice. Partial assertions are useful when only part of the output is the contract. The first test states one rule, "every slug starts with the product prefix", and stays green if the rest of the format changes for a good reason. When a partial assertion fails, xUnit prints the full actual string, so you still see what came out.
Note the argument order. String assertions take the expected fragment first and the actual string second, like Assert.Equal. Assert.DoesNotContain("ı", slug) checks that no dotless i leaked into the URL, which is a real risk for this input.
Format Contracts with Regular Expressions
M02.XUnitBasics.Tests/StringAssertionTests.cs
Assert.Matches is the right tool when the contract is a shape rather than a fixed value. The pattern says: the prefix, then groups of lowercase letters and digits separated by single dashes, with no dash at the end. That one line covers double dashes, trailing dashes and uppercase letters for every input. Assert.DoesNotMatch adds a negative check for uppercase letters, including the Turkish ones.
Keep regex patterns in tests simple. A pattern that needs its own unit tests to understand has stopped documenting the contract.
To choose between Equal and Matches, ask whether a different but valid output should pass. If urun/seffaf-canta-42 is the only correct answer, assert it with Equal. If any slug that follows the rules is fine, describe the rules with Matches. Many teams use both: a few Equal tests for known examples, and one Matches test for the general shape.
The Pitfall: Unstated Comparison Rules
The most frequent bug in string tests is not saying how two strings should be compared. Case sensitivity and culture are part of the behaviour, so write them down:
M02.XUnitBasics.Tests/StringAssertionTests.cs
Assert.Equal has an ignoreCase parameter, and Assert.Contains, StartsWith and EndsWith accept a StringComparison. Use them instead of calling ToLower() on both sides, which hides the rule and depends on the current culture.
The last line shows why culture matters. Turkish has two letters i: dotted (i/İ) and dotless (ı/I). An ordinal, case-insensitive comparison uses invariant case rules, so it treats I and i as equal and I and ı as different. A culture-aware comparison with tr-TR does the opposite. The same code can therefore give different answers on a developer machine and a build server with a different culture. For technical text such as slugs, codes and identifiers, use StringComparison.Ordinal or OrdinalIgnoreCase. Use a culture only when you compare text for humans and the culture is known.
The test also shows that OrdinalIgnoreCase never folds letters to ASCII: ş and S stay different letters. That is why SlugGenerator maps them explicitly with TurkishMap instead of hoping that lowercasing will do it.
Invalid Input
M02.XUnitBasics.Tests/StringAssertionTests.cs
Whitespace-only input is part of the text contract too. ArgumentException.ThrowIfNullOrWhiteSpace rejects it, and the test pins that rule down. Exception assertions get a full lesson of their own later in this series.
Summary
StartsWith,EndsWithandContainscheck one part of a text contract and print the full string on failure.Assert.Matcheschecks a format, such as "lowercase letters, digits and single dashes", for any input.- Always state the comparison rule: use
ignoreCase: trueor aStringComparisoninstead ofToLower(). - Prefer ordinal comparison for technical text. Culture-aware rules, such as Turkish dotted and dotless i, change results between machines.