Search code examples
c#unit-testingautofixture

Is there a better way to do these boiler plate tests in C#?


Currently using AutoFixture for the boiler plate code of guard methods. But is there a better way to do the rest of the boiler plate code in the unit tests? Or is there no need to test in the first place?

        fixture.Create<TestClass>();
        var testException = new ArgumentNullBehavior();
        var assertion = new GuardClauseAssertion(fixture, testException);
        assertion.Verify(typeof(TestClass).GetConstructors());

        //Boiler plate part below:
        var testClass = new TestClass(lang, refer, link, info, title, description);
        Assert.AreEqual(lang, testClass.Lang);
        Assert.AreEqual(refer, testClass.Refer);
        Assert.AreEqual(link, testClass.Link);
        Assert.AreEqual(info, testClass.Info);
        Assert.AreEqual(title, testClass.Title);
        Assert.AreEqual(description, testClass.Description);

Solution

  • I would recommend installing FluentAssertions package:
    NuGet\Install-Package FluentAssertions -Version 6.9.0

    Then you could replace those manual assertions using object equivalency method: actualTestClass.Should().BeEquivalentTo(expectedTestClass);

    In general this package has various functionality that might save you from writing this boilerplate code you have posted. Ex.: checking if DateTime fields are close to certain value.

    Here's the link for docs - https://fluentassertions.com/objectgraphs/