TNG / ArchUnitNET

A C# architecture test library to specify and assert architecture rules in C# for automated testing.
Apache License 2.0
826 stars 55 forks source link

Circular Dependency Issue when managing a whitelist of dependencies #255

Open BrunoBeraud opened 2 months ago

BrunoBeraud commented 2 months ago

Hello,

Here's a test to check that my usecase class has only authorized dependencies

private readonly IObjectProvider<Interface> UseCaseInterfaces = Classes().That().HaveNameEndingWith("UseCase");

[Fact]
public void UseCasesNotHaveAnyDependenciesExceptCore()
{
    string[] whitelistDependenciesRegex = ["^System", ".*\\.Core\\..*"];
    Classes().That().Are(UseCaseClasses)
        .Should().NotDependOnAnyTypesThat().DoNotResideInNamespace(
            pattern: string.Join("|", whitelistDependenciesRegex),
            useRegularExpressions: true)
            .Because("UseCases must contains only application business concern and must not be impacted by any infrastructure concern")
            .Check(Architecture);
}

// Class to check
internal class GetAllUseCase(IRepository Repository) : IGetAllUseCase
{
    private IRepository _repository;

    public async Task<Result<IEnumerable<Entity>>> GetAllAsync()
    {
        var resultat = await __repository.GetAllAsync();
        return Result<IEnumerable<Entity>>.Success(resultat);
    }
}

In this example, the Core and System namespaces are the only authorized dependencies. Core contains the IRepository interface. The problem is that the "_repository" member of the usecase class is considered a dependency, which will cause the test to fail because "GetAllUseCase" depends on "GetAllUseCase"... I can't whitelist the GetAllUseCase class because I have several use cases and this test needs to cover them all but I don't want to allow them to depend on this one (in fact more generally I don't want any of them to depend on any of the others).

How do I do this?

Thank !