Skip to content

Add new namespace assertions to TypeSelectorAssertions #1175

@kimsey0

Description

@kimsey0

Description

Currently, TypeSelectorAssertions only contains methods for asserting that types are (not) decorated with specific attributes, e.g., BeDecoratedWith<>. However, TypeSelector contains more selectors that would also be useful as assertions.

One such group of selectors filter on the namespace of types and contain the methods ThatAreInNamespace, ThatAreNotInNamespace, ThatAreUnderNamespace, and ThatAreNotUnderNamespace. Corresponding assertions could be named BeInNamespace, NotBeInNamespace, BeUnderNamespace, and NotBeUnderNamespace.

Use case

A concrete use case I have that prompted this suggestion is that the JsonSubTypes library, which is used to deserialize JSON into one of a number of subclasses based on a discriminator value, only supports deserializing into subclasses in the same namespace as the base class. Therefore, I would like to be able to write a test that asserts that all subclasses of a specific class are in the same namespace as it, à la:

AllTypes.From(baseClassAssembly).ThatDeriveFrom<BaseClass>().Should().BeInNamespace(baseClassNamespace);

Draft implementation as custom extension

To support the use case above, I have implemented the BeInNamespace assertion in our project as the following custom extension:

public static class TypeSelectorAssertionsExtensions
{
    public static AndConstraint<TypeSelectorAssertions> BeInNamespace(this TypeSelectorAssertions typeSelectorAssertions, string @namespace, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
               .BecauseOf(because, becauseArgs)
               .ForCondition(@namespace != null)
               .FailWith("Types cannot have a null namespace")
               .Then
               .Given(() => typeSelectorAssertions.Subject)
               .ForCondition(types => types.All(type => type.Namespace == @namespace))
               .FailWith("Expected types to be in namespace {0}{reason}, but found {1}.",
                   _ => @namespace, types => types.Where(type => type.Namespace != @namespace));

        return new AndConstraint<TypeSelectorAssertions>(typeSelectorAssertions);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions