Search code examples
c#nunitautofixture

GuardClauseAssertion does not fail if limited to only public constructors


Why does this unit test not fail when no guard clause is present?

  [Test]
  public void ConstructorLooksGuardedAgainstNulls()
  {
    // ARRANGE
    var fixture = new Fixture();
    var assertion = fixture.Create<GuardClauseAssertion>();

    // ACT & ASSERT
    assertion.Verify(typeof(TestClass).GetConstructors(BindingFlags.Public));
  }

Classes used in unit test:

  public class TestBaseClass
  {
    private readonly string _firstDependency;
    private readonly string _secondDependency;

    protected TestBaseClass(string firstDependency, string secondDependency)
    {
      _firstDependency = firstDependency;
      _secondDependency = secondDependency;
    }
  }

  public class TestClass : TestBaseClass
  {
    public TestClass(string firstDependency)
      : base(firstDependency, string.Empty)
    {
    }
  }

I removed all the irrelevant lines.


Solution

  • This will return all public constructors, and then the test will fail as expected:

    typeof(TestClass).GetConstructors()
    

    The version with the BindingFlags parameter doesn't return the public constructors (although it reads like it really should do). Because no constructor are found, the test passes

    typeof(TestClass).GetConstructors(BindingFlags.Public)