04 Jan 2024



Beginner

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#:

  1. Basic Assertions:

    • result.Should().NotBeNull();
    • result.Should().BeNull();
    • result.Should().Be(expected);
  2. Numeric Assertions:

    • result.Should().BeGreaterThan(5);
    • result.Should().BeLessThan(10);
    • result.Should().BeInRange(5, 10);
  3. String Assertions:

    • result.Should().StartWith("prefix");
    • result.Should().EndWith("suffix");
    • result.Should().Contain("substring");
    • result.Should().Match("*pattern*"); (supports wildcard matching)
  4. Collection Assertions:

    • collection.Should().Contain(item);
    • collection.Should().NotContain(item);
    • collection.Should().HaveCount(expectedCount);
    • collection.Should().BeEquivalentTo(expectedCollection);
  5. Object Equality:

    • result.Should().BeEquivalentTo(expectedObject);
    • result.Should().BeOfType<ExpectedType>();
    • result.Should().BeAssignableTo<AssignableType>();
  6. Exception Handling:

    • Action act = () => SomeMethod(); act.Should().Throw<ExpectedException>();
    • Action act = () => SomeMethod(); act.Should().ThrowExactly<ExpectedException>().WithMessage("Exception message");
  7. Property and Field Assertions:

    • result.Should().HaveProperty(propertyName);
    • result.Should().HaveField(fieldName);
    • result.Should().HavePropertyWithValue(propertyName, expectedValue);
  8. DateTime Assertions:

    • dateTime.Should().BeBefore(endDateTime);
    • dateTime.Should().BeAfter(startDateTime);
    • dateTime.Should().BeWithin(expectedTimeSpan).Before(endDateTime);
  9. Collection Ordering:

    • collection.Should().BeInAscendingOrder();
    • collection.Should().BeInDescendingOrder();
  10. Custom Assertions:

    • result.Should().SatisfyRespectively(firstAssertion, secondAssertion, ...);
    • result.Should().Match(customPredicate);

Certainly! Here are some additional Fluent Assertions that you might find useful:

  1. Collection Element Assertions:

    • collection.Should().OnlyContain(element => element.Property > 0);
    • collection.Should().NotContainNulls();
    • collection.Should().HaveElementAt(index, expectedElement);
  2. Collection Comparison:

    • collection1.Should().Equal(collection2);
    • collection1.Should().Equal(collection2, (obj1, obj2) => obj1.Property == obj2.Property);
  3. Dictionary Assertions:

    • dictionary.Should().ContainKey(key);
    • dictionary.Should().NotContainKey(key);
    • dictionary.Should().ContainValue(value);
    • dictionary.Should().NotContainValue(value);
  4. Collection Size Assertions:

    • collection.Should().BeEmpty();
    • collection.Should().NotBeEmpty();
    • collection.Should().HaveCountGreaterThan(5);
    • collection.Should().HaveSameCount(otherCollection);
  5. DateTime Offset Assertions:

    • dateTimeOffset.Should().BeCloseTo(expectedDateTimeOffset, precision);
    • dateTimeOffset.Should().HaveDate(expectedYear, expectedMonth, expectedDay);
    • dateTimeOffset.Should().HaveTime(expectedHour, expectedMinute, expectedSecond);
  6. String Comparison:

    • result.Should().BeEquivalentTo(expectedString, options => options.WithStrictOrdering());
    • result.Should().BeEquivalentTo(expectedString, options => options.IgnoringCase);
  7. Assertions on Nullable Types:

    • nullableValue.Should().HaveValue();
    • nullableValue.Should().NotHaveValue();
    • nullableValue.Should().Be(expectedValue);
  8. Assertions on Types with Properties:

    • result.Should().HaveProperty("PropertyName");
    • result.Should().HavePropertyWithValue("PropertyName", expectedValue);
  9. Assertions on Enumerables:

    • enumerable.Should().ContainSingle(item => item.Property == expectedValue);
    • enumerable.Should().OnlyContain(item => item.IsValid());
  10. Assertions on XML Documents:

    • xmlDoc.Should().HaveElement("RootElement").Which.Should().HaveAttribute("Attribute", "Value");
    • xmlDoc.Should().HaveElement("RootElement").Which.Should().HaveValue("ExpectedValue");
  11. 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);
  12. Assertions on Events:

    • eventPublisher.Should().Raise("EventName");
    • eventPublisher.Should().Raise<EventArgsType>("EventName");
    • eventPublisher.Should().NotRaise("EventName");
  13. Assertions on Files:

    • fileInfo.Should().Exist();
    • fileInfo.Should().HaveExtension(".txt");
    • fileInfo.Should().HaveLength(expectedLength);
  14. Assertions on Streams:

    • stream.Should().NotBeNull().And.HaveSameContentAs(otherStream);
    • stream.Should().HaveLength(expectedLength);
  15. Assertions on Web APIs (using FluentAssertions.Web):

    • response.Should().HaveStatusCode(HttpStatusCode.OK);
    • response.Should().HaveHeader("headerName", "headerValue");
    • response.Should().HaveContent("expectedContent");
  16. Assertions on Dependency Injection:

    • container.Should().HaveRegistrationFor<IService>();
    • container.Should().NotHaveRegistrationFor<IService>();
    • container.Should().HaveResolved<IService>();
  17. Assertions on Parallel Execution:

    • Action action = () => SomeParallelMethod(); action.Should().NotThrow();
    • Action action = () => SomeParallelMethod(); action.Should().CompleteWithin(timeout);
  18. Assertions on JSON Documents:

    • jsonDocument.Should().HaveElement("propertyName").WithValue("expectedValue");
    • jsonDocument.Should().HaveArray("arrayName").Which.Should().HaveCount(3);
  19. Assertions on GraphQL Responses (using FluentAssertions.Json):

    • graphQLResponse.Should().HaveData("propertyName").EqualTo("expectedValue");
    • graphQLResponse.Should().HaveErrors();
  20. 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.
unit-test
fluent-assertions
c#