Skip to content

Finding a call inside a async method does not work (sometimes) #392

@Urganot

Description

@Urganot

Hi,

I currently struggle with a really weird issue. What I am trying to do is to write a test that makes sure that DateTime.Now is never used. My code works most of the time. I observed that if a method uses the async keyword, the test will not find a call to DateTime.Now

This is my test code:

private static readonly Architecture architecture =
        new ArchLoader().LoadAssemblies(typeof(Startup).Assembly,
                                        typeof(DateTime).Assembly,
                                        typeof(GuidelineTests).Assembly)
                        .Build();

    [Fact]
    public void NameSpace_UsageCheck_NoDateTimeNowForGettingTimestamps()
    {
        var dateTimeNowGetMethodName = typeof(DateTime).GetProperty(nameof(DateTime.Now))?.GetGetMethod()?.Name;
        dateTimeNowGetMethodName.Should().NotBeNull();

        var methods = MethodMembers()
                     .That()
                     .AreDeclaredIn(typeof(DateTime))
                     .And()
                     .HaveFullNameContaining(dateTimeNowGetMethodName);

        var types = Types().That().DoNotResideInNamespace(typeof(DateTime).Namespace).And().DoNotHaveFullName(typeof(GuidelineTests).FullName);

        var method = MethodMembers().That().HaveNameContaining("InsertAsync_ConnectionInformationPersisted3").GetObjects(architecture).ToList();
        
        var rule = MethodMembers()
                  .That()
                  .AreDeclaredIn(types)
                  .Should()
                  .NotCallAny(methods);

        rule.Check(architecture);
    }

The weird thing now is that when I tried to replicate this behaviour in a new project, it suddenly works as I expect it.
You can find the test project here: https://github.com/Urganot/ArchUnitAsyncIssue
Unfortunately I am unable to share code from the original project.

If I run my tests in the demo project, all usages of DateTime.Now will be found. In my original project, only calls from non async methods are found.
To test this, I just changed the signature.

In my original project, this DateTime.Now will NOT be found.

    [Fact]
    public async Task Test1()
    {
        var timeStamp = DateTime.Now;
    }

But only changing the signature to

    [Fact]
    public void Test1()
    {
        var timeStamp = DateTime.Now;
    }

Makes it so that it IS found

Does anybody have any idea, what is happening here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions