Skip to content

Bug: Assert.That(IEnumerable<Type>, Has.All.Property(nameof(Type.Namespace)) fails. #4259

Description

@andrewimcclement

Originally posted as https://stackoverflow.com/questions/74475185.
Using NUnit v3.13.2, .NET Framework 4.8, running using ReSharper test runner. I'll try to find some time to run this with just nunit console runner and/or actually debug this myself.

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 ....
(Note the StartsWith is irrelevant.)

However, the equivalent non-collection assert Has.Property(nameof(Type.Namespace)).StartsWith("MyNamespace") succeeds.
I assume that this is a bug, if not, let's make sure the documentation is clear about how this is supposed to work.

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()

Potentially relevant comment from Ralf on the stackoverflow question:
Debugging through NUnit i would assume a bug here. When using Property on the AllItemConstraint there is an extra handling when the thing in there is already a type. It does not create a type on the type that you would need for your code to work. Now it searches "Namespace" on Foo and not on the type object of Foo.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions