Search code examples
c#nunit

Why does Has.All.Property(nameof(Type.Namespace)) fail when attempting to assert on a collection of Types using NUnit?


I want to assert that all the types I am interested in are in the expected namespace using NUnit.

IReadOnlyCollection<Type> types = GetInterestingTypes(); // Method defined elsewhere.
Assert.That(types, Has.All.Property(nameof(Type.Namespace)).StartsWith("MyNamespace"));

This fails with ArgumentException Property Namespace not found on ....

However, the equivalent non-collection assert Has.Property(nameof(Type.Namespace)).StartsWith("MyNamespace") succeeds.

Minimal reproducible example:

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

using NUnit.Framework;

namespace MyNamespace
{
    internal class MyTests
    {
        [Test]
        public void TestsWithinNamespace()
        {
            var types = new[] {typeof(Foo), typeof(NestedNamespace.Bar)};

            foreach (var type in types)
            {
                // Passes
                Assert.That(type, Has.Property(nameof(Type.Namespace)).StartsWith("MyNamespace"));
            }

            // Fails
            Assert.That(types, Has.All.Property(nameof(Type.Namespace)).StartsWith("MyNamespace"));
        }
    }

    public class Foo { }

    namespace NestedNamespace
    {
        public class Bar { }
    }
}

When running this test, we get

System.ArgumentException : Property Namespace was not found on MyNamespace.Foo.
Parameter name: name
   at NUnit.Framework.Constraints.PropertyConstraint.ApplyTo[TActual](TActual actual)
   at NUnit.Framework.Constraints.AllItemsConstraint.ApplyTo[TActual](TActual actual)
   at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression, String message, Object[] args)
   at MyNamespace.MyTests.TestsWithinNamespace()

Solution

  • This bug in NUnit has been fixed, however a new release of NUnit containing the fix has not yet been released.
    Issue: https://github.com/nunit/nunit/issues/4259
    Pull request fixing issue: https://github.com/nunit/nunit/pull/4285