04 Jan 2024
FluentAssertions is a popular assertion library for C# that provides a fluent syntax for writing clear and concise assertions in unit tests. Here's a guide to help you get started with FluentAssertions in C#:
-
Basic Assertions:
result.Should().NotBeNull();result.Should().BeNull();result.Should().Be(expected);
-
Numeric Assertions:
result.Should().BeGreaterThan(5);result.Should().BeLessThan(10);result.Should().BeInRange(5, 10);
-
String Assertions:
result.Should().StartWith("prefix");result.Should().EndWith("suffix");result.Should().Contain("substring");result.Should().Match("*pattern*");(supports wildcard matching)
-
Collection Assertions:
collection.Should().Contain(item);collection.Should().NotContain(item);collection.Should().HaveCount(expectedCount);collection.Should().BeEquivalentTo(expectedCollection);
-
Object Equality:
result.Should().BeEquivalentTo(expectedObject);result.Should().BeOfType<ExpectedType>();result.Should().BeAssignableTo<AssignableType>();
-
Exception Handling:
Action act = () => SomeMethod(); act.Should().Throw<ExpectedException>();Action act = () => SomeMethod(); act.Should().ThrowExactly<ExpectedException>().WithMessage("Exception message");
-
Property and Field Assertions:
result.Should().HaveProperty(propertyName);result.Should().HaveField(fieldName);result.Should().HavePropertyWithValue(propertyName, expectedValue);
-
DateTime Assertions:
dateTime.Should().BeBefore(endDateTime);dateTime.Should().BeAfter(startDateTime);dateTime.Should().BeWithin(expectedTimeSpan).Before(endDateTime);
-
Collection Ordering:
collection.Should().BeInAscendingOrder();collection.Should().BeInDescendingOrder();
-
Custom Assertions:
result.Should().SatisfyRespectively(firstAssertion, secondAssertion, ...);result.Should().Match(customPredicate);
Certainly! Here are some additional Fluent Assertions that you might find useful:
-
Collection Element Assertions:
collection.Should().OnlyContain(element => element.Property > 0);collection.Should().NotContainNulls();collection.Should().HaveElementAt(index, expectedElement);
-
Collection Comparison:
collection1.Should().Equal(collection2);collection1.Should().Equal(collection2, (obj1, obj2) => obj1.Property == obj2.Property);
-
Dictionary Assertions:
dictionary.Should().ContainKey(key);dictionary.Should().NotContainKey(key);dictionary.Should().ContainValue(value);dictionary.Should().NotContainValue(value);
-
Collection Size Assertions:
collection.Should().BeEmpty();collection.Should().NotBeEmpty();collection.Should().HaveCountGreaterThan(5);collection.Should().HaveSameCount(otherCollection);
-
DateTime Offset Assertions:
dateTimeOffset.Should().BeCloseTo(expectedDateTimeOffset, precision);dateTimeOffset.Should().HaveDate(expectedYear, expectedMonth, expectedDay);dateTimeOffset.Should().HaveTime(expectedHour, expectedMinute, expectedSecond);
-
String Comparison:
result.Should().BeEquivalentTo(expectedString, options => options.WithStrictOrdering());result.Should().BeEquivalentTo(expectedString, options => options.IgnoringCase);
-
Assertions on Nullable Types:
nullableValue.Should().HaveValue();nullableValue.Should().NotHaveValue();nullableValue.Should().Be(expectedValue);
-
Assertions on Types with Properties:
result.Should().HaveProperty("PropertyName");result.Should().HavePropertyWithValue("PropertyName", expectedValue);
-
Assertions on Enumerables:
enumerable.Should().ContainSingle(item => item.Property == expectedValue);enumerable.Should().OnlyContain(item => item.IsValid());
-
Assertions on XML Documents:
xmlDoc.Should().HaveElement("RootElement").Which.Should().HaveAttribute("Attribute", "Value");xmlDoc.Should().HaveElement("RootElement").Which.Should().HaveValue("ExpectedValue");
-
Assertions on Linq Queries:
collection.Should().ContainSingle(item => item.Property == expectedValue);collection.Should().OnlyContain(item => item.IsValid());collection.Should().HaveCountGreaterThan(5).And.OnlyContain(item => item.Property > 0);
-
Assertions on Events:
eventPublisher.Should().Raise("EventName");eventPublisher.Should().Raise<EventArgsType>("EventName");eventPublisher.Should().NotRaise("EventName");
-
Assertions on Files:
fileInfo.Should().Exist();fileInfo.Should().HaveExtension(".txt");fileInfo.Should().HaveLength(expectedLength);
-
Assertions on Streams:
stream.Should().NotBeNull().And.HaveSameContentAs(otherStream);stream.Should().HaveLength(expectedLength);
-
Assertions on Web APIs (using FluentAssertions.Web):
response.Should().HaveStatusCode(HttpStatusCode.OK);response.Should().HaveHeader("headerName", "headerValue");response.Should().HaveContent("expectedContent");
-
Assertions on Dependency Injection:
container.Should().HaveRegistrationFor<IService>();container.Should().NotHaveRegistrationFor<IService>();container.Should().HaveResolved<IService>();
-
Assertions on Parallel Execution:
Action action = () => SomeParallelMethod(); action.Should().NotThrow();Action action = () => SomeParallelMethod(); action.Should().CompleteWithin(timeout);
-
Assertions on JSON Documents:
jsonDocument.Should().HaveElement("propertyName").WithValue("expectedValue");jsonDocument.Should().HaveArray("arrayName").Which.Should().HaveCount(3);
-
Assertions on GraphQL Responses (using FluentAssertions.Json):
graphQLResponse.Should().HaveData("propertyName").EqualTo("expectedValue");graphQLResponse.Should().HaveErrors();
-
Custom Assertion Rules:
- Fluent Assertions allows you to create custom assertion rules. You can define your own extension methods to encapsulate complex assertions specific to your application.