Mastering Fluent Assertions in C# – Testing Collections Made Simple
Are your collection assertions still stuck with Assert.Contains and manual loops? It’s time to upgrade.
In this post, you’ll use Fluent Assertions with xUnit to write clear, maintainable, intention-revealing tests for lists and collections in C#. Whether you're validating API results or a filter operation, these patterns keep tests readable and failures helpful.
๐ง Prerequisites
Add these packages to your test project (NuGet):
Install-Package FluentAssertions
Install-Package xunit
๐ Sample Collection
Examples below use a simple list:
var fruits = new List<string> { "apple", "banana", "cherry" };
✅ Go-To Collection Assertions
๐ 1) Contains a specific item
fruits.Should().Contain("banana");
๐งพ 2) Contains multiple items
fruits.Should().Contain(new[] { "apple", "cherry" });
๐ 3) Elements in a specific order
fruits.Should().ContainInOrder("apple", "banana", "cherry");
๐ฏ 4) Exact match (values + order)
fruits.Should().Equal(new[] { "apple", "banana", "cherry" });
๐ซ 5) Not empty + expected count
fruits.Should().NotBeEmpty();
fruits.Should().HaveCount(3);
๐งช 6) All elements satisfy a condition
fruits.Should().OnlyContain(f => f.Length >= 5);
๐ฌ 7) Starts/Ends with
fruits.Should().StartWith("apple");
fruits.Should().EndWith("cherry");
๐งช Real-World Example
using FluentAssertions;
using Xunit;
public class CollectionTests
{
[Fact]
public void FruitList_Should_Meet_Requirements()
{
var fruits = new List<string> { "apple", "banana", "cherry" };
fruits.Should().NotBeNullOrEmpty()
.And.HaveCount(3)
.And.ContainInOrder("apple", "banana", "cherry")
.And.OnlyContain(f => f.Length >= 5);
}
}
๐ผ When to Use These Patterns
- Validating search/filter results
- Verifying API response collections
- Comparing pre/post transformation outputs
- Improving team readability and faster failure diagnosis
Fluent Assertions shines by producing descriptive failure messages—so you spend less time reproducing and more time fixing.
๐ Previous Post in the Series
If you’re just joining, don’t miss Part 1:
๐ Write Cleaner Unit Tests with Fluent Assertions in C#
๐ฃ I’d Love Your Feedback
Was this helpful? Have scenarios you want covered (e.g., dictionaries, sets, or deep-object comparisons)? Share your suggestions, and I’ll explore them next.
๐ Stay connected and follow HGDevHub for more micro tools, automation scripts, and tech walkthroughs:
- ๐ฆ Follow on X (Twitter)
- ✍️ Follow on Medium
- ๐️ Explore tools on Gumroad
- ๐ฅ Join the Reddit space (Coming Soon)
๐ฌ Your input helps shape what comes next!
๐ฉ Stay Tuned
More automation scripts and micro-tools coming soon. Follow HGDevHub for fresh tools that save time and spark ideas.
Excellent guide! Made working with collections in Fluent Assertions so much simpler and clearer. The examples really helped me understand best practices.
ReplyDelete