Skip to content

[Bug]: Nullability of event args is ignored in generated mocks #5425

@Kaskadee

Description

@Kaskadee

Description

If the generic type argument of a EventHandler<T> is nullable, the nullability is ignored in the generated mock causing the warning CS8604: Possible null reference argument for parameter 'e' in 'void EventHandler<string>.Invoke(object? sender, string e)'.

// <auto-generated/>
#nullable enable

namespace TUnit.Mocks.Generated.Sandbox
{
    public sealed class IFooMock : global::TUnit.Mocks.Mock<global::Sandbox.IFoo>, global::Sandbox.IFoo
    {
        [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
        internal IFooMock(global::Sandbox.IFoo mockObject, global::TUnit.Mocks.MockEngine<global::Sandbox.IFoo> engine)
            : base(mockObject, engine) { }

        event global::System.EventHandler<string> global::Sandbox.IFoo.Something { add => Object.Something += value; remove => Object.Something -= value; } // Should be `EventHandler<string?>` instead
    }
}

Expected Behavior

The nullability of the generic type argument is correctly copied to the generated mock implementation

Actual Behavior

The nullability is ignored causing CS8604 in the generated Raise_Something of the MockImplFactory class (which correctly uses a nullable string?)

Steps to Reproduce

using TUnit.Mocks.Generated.Sandbox;

namespace Sandbox;

public interface IFoo {
    event EventHandler<string?> Something;
}

public class TestClass {
    [Test]
    public async Task SomeTest() {
        IFooMock foo = IFoo.Mock();
    }
}

TUnit Version

1.28.7-beta

.NET Version

.NET 10.0

Operating System

Windows

IDE / Test Runner

JetBrains Rider

Error Output / Stack Trace

Restore complete (1.2s)
  Sandbox net10.0 succeeded with 1 warning(s) (1.5s) → Sandbox/bin/Debug/net10.0/Sandbox.dll
    /mnt/x/Sandbox/Sandbox/obj/Debug/net10.0/TUnit.Mocks.SourceGenerator/TUnit.Mocks.SourceGenerator.MockGenerator/Sandbox_IFoo_MockImplFactory.g.cs(29,46): warning CS8604: Possible null reference argument for parameter 'e' in 'void EventHandler<string>.Invoke(object? sender, string e)'.

Build succeeded with 1 warning(s) in 3.2s

Additional Context

No response

IDE-Specific Issue?

  • I've confirmed this issue occurs when running via dotnet test or dotnet run, not just in my IDE

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions