#1568·moq

.RaiseAsync throws exception when used with a void delegate, no exception info for wrong using

Author: KeugonCreated Jun 27, 2025Updated Aug 31, 2026
Labelsbugstale

Describe the Bug

When raising a event with .RaiseAsync() with a void Delegate like public delegate void MySampleDelegate(int nummer, bool istAktiviert); the .RaiseAsync() methode gives a System.NullReferenceException because it expects a delegate with Task as return type

Steps to Reproduce

csharp
[TestClass]
public sealed class ReproTest
{
  [TestMethod]
  public async Task TestMethod1()
  {
    Mock<ICommunicator> mockCommunicator = new Mock<ICommunicator>();
    WorkingClass proband = new WorkingClass(mockCommunicator.Object);

    await mockCommunicator.RaiseAsync(e => e.VaccumPumpActivationEvent += null, 1, true);

  }
}
csharp
public class WorkingClass
{
  private readonly ICommunicator _Communicator;
  public WorkingClass(ICommunicator kommunikator)
  {
    this._Communicator = kommunikator;
    this._Communicator.VaccumPumpActivationEvent += this.Event_VaccumPumpActivation;
  }

  private void Event_VaccumPumpActivation(int nummer, bool istAktiviert)
  {
    Console.WriteLine($"EventFired with {nummer}, and {istAktiviert}");
  }
}

public delegate void VaccumPumpActivationDelegate(int nummer, bool istAktiviert);
public interface ICommunicator
{
  public event VaccumPumpActivationDelegate VaccumPumpActivationEvent;
}

Expected Behavior

The .RaiseAsync() methode should describe that such a Exception can occur and the Exception should contain a informativ description why it doesnt work eg. Event is not of return type Task.

Exception with Stack Trace

System.NullReferenceException
  HResult=0x80004003
  Message = Object reference not set to an instance of an object.
  Source = ConsoleAppBastelProjekt.UnitTests
  Stacktrace:
   bei ConsoleAppBastelProjekt.UnitTests.Test1.<TestMethod1>d__0.MoveNext() in D:\Git\ForeignRepos\ConsoleAppBastelProjekt\ConsoleAppBastelProjekt.UnitTests\Test1.cs: Zeile14

Version Info

Application Project tested with .net8 and ´.net9´ Test Project

xml
<ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
    <PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" Version="17.12.6" />
    <PackageReference Include="Microsoft.Testing.Extensions.TrxReport" Version="1.4.3" />
    <PackageReference Include="Moq" Version="4.20.72" />
    <PackageReference Include="MSTest" Version="3.6.4" />
  </ItemGroup>

Additional Info

This Issue got originaly resolved and explained to me in this Thread https://stackoverflow.com/questions/79680262/moq-raiseasync-results-in-system-nullreferenceexception-moq-raise-works-fine/

Back this issue Back this issue