TNG / ArchUnitNET

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

Analyse dependencies of async methods #138

Closed wdhofmann closed 2 years ago

wdhofmann commented 2 years ago

Background

Create a class that has an async method which uses another class:

namespace SomeNamespace
{
    public class ClassWithAsyncMethod
    {
        public async void MethodAsync()
        {
            var otherClass = new OtherClass();
        }
    }

    public class OtherClass
    {
    }
}

Create a rule that verifies that ClassWithAsyncMethod does not depend on OtherClass:

[Fact]
public void Class_should_not_depend_on_other_class()
{
    var rule = Types().That().Are(typeof(ClassWithAsyncMethod)).
        Should().NotDependOnAny(Types().That().Are(typeof(OtherClass)));

    rule.Check(Architecture);
}

Expected result

Rule fails.

Actual result

Rule passes.

Reason

When using the async keyword the compiler creates a nested helper class that contains the logic of MethodAsync (the instantiation of OtherClass). MethodAsync itself contains just the logic to use the helper class. The analysis scans MethodAsync but not the nested helper class. So the dependency to OtherClass is not detected.

Solution

Extend analysis to scan the nested helper class also.

fgather commented 2 years ago

Thanks a lot, the fix is contained in 0.8.5