Lesson 13 of 93 · 5 min read · Updated

String Assertions in xUnit: StartsWith, Contains, Matches and Explicit StringComparison

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

  1. .NET 11 SDK
  2. 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

using System.Globalization;
using System.Text;

namespace M02.XUnitBasics;

public static class SlugGenerator
{
// Maps Turkish characters to their ASCII equivalents.
private static readonly Dictionary<char, string> TurkishMap = new()
{
['ı'] = "i", ['İ'] = "i", ['ş'] = "s", ['Ş'] = "s",
['ğ'] = "g", ['Ğ'] = "g", ['ü'] = "u", ['Ü'] = "u",
['ö'] = "o", ['Ö'] = "o", ['ç'] = "c", ['Ç'] = "c",
};

/// <summary>"Kırmızı Ürün 5" → "urun/kirmizi-urun-5"</summary>
public static string Create(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);

var builder = new StringBuilder("urun/");
var previousWasDash = false;

// We do NOT rely on lowercasing alone: we solve the Turkish 'I' problem
// on purpose with TurkishMap, then lowercase with the invariant culture.
foreach (var ch in name.Trim())
{
if (TurkishMap.TryGetValue(ch, out var replacement))
{
builder.Append(replacement);
previousWasDash = false;
}
else if (char.IsLetterOrDigit(ch))
{
builder.Append(char.ToLower(ch, CultureInfo.InvariantCulture));
previousWasDash = false;
}
else if (!previousWasDash)
{
builder.Append('-');
previousWasDash = true;
}
}

return builder.ToString().TrimEnd('-');
}
}

Prefix, Suffix and Substrings

M02.XUnitBasics.Tests/StringAssertionTests.cs

[Fact]
public void Create_StartsWithProductPrefix()
{
var slug = SlugGenerator.Create("Mekanik Klavye");

Assert.StartsWith("urun/", slug);
Assert.EndsWith("klavye", slug);
}

[Fact]
public void Create_ContainsExpectedWords()
{
var slug = SlugGenerator.Create("Kırmızı Işıklı Gözlük");

Assert.Contains("kirmizi", slug);
Assert.Contains("isikli", slug);
Assert.DoesNotContain("ı", slug);
}

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

[Fact]
public void Create_MatchesSlugPattern()
{
var slug = SlugGenerator.Create("Şeffaf Çanta 42");

// We check the "format contract" with a regex:
// only lowercase letters, digits and dashes.
Assert.Matches("^urun/[a-z0-9]+(-[a-z0-9]+)*$", slug);
Assert.DoesNotMatch("[A-ZÇĞİÖŞÜ]", slug);
}

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

[Fact]
public void Compare_WithExplicitStringComparison()
{
const string actual = "Mekanik Klavye";

// If case is NOT part of the behaviour, say so explicitly.
Assert.Equal("mekanik klavye", actual, ignoreCase: true);

Assert.Contains("KLAVYE", actual, StringComparison.OrdinalIgnoreCase);

// The Turkish 'I' trap: culture-sensitive comparison can give different results.
// That is why Ordinal is preferred for technical text (slugs, codes, ids).
Assert.False(string.Equals("ISIK", "ışık", StringComparison.OrdinalIgnoreCase));
}

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

[Fact]
public void Create_WithBlankInput_Throws()
{
Assert.Throws<ArgumentException>(() => SlugGenerator.Create(" "));
}

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

  1. StartsWith, EndsWith and Contains check one part of a text contract and print the full string on failure.
  2. Assert.Matches checks a format, such as "lowercase letters, digits and single dashes", for any input.
  3. Always state the comparison rule: use ignoreCase: true or a StringComparison instead of ToLower().
  4. Prefer ordinal comparison for technical text. Culture-aware rules, such as Turkish dotted and dotless i, change results between machines.