Moq.RaiseAsync触发事件时抛出NullReferenceException但Raise方法正常的问题求助
大家好,我最近在给一个.NET 8(.NET 9环境下也会出现同样问题)的项目写单元测试,用的是Moq 4.20.72版本,碰到了一个棘手的问题:
当我用同步方法mockCommunicator.Raise(e => e.VaccumPumpActivationEvent += null, 1, true);触发事件时,一切运行正常;但换成异步的await mockCommunicator.RaiseAsync(e => e.VaccumPumpActivationEvent += null, 1, true);就会直接抛出NullReferenceException。我翻了下Moq的源码,发现Mock.RaiseEventAsync内部会调用(Task)Mock.RaiseEvent(mock, expression, parts, arguments);,而RaiseEvent方法里有个分支可能会返回null,这会不会是问题根源?不过更大的概率应该是我用错了RaiseAsync的用法?
下面是我的最小复现代码:
应用项目核心代码
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; }
测试项目依赖配置
<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>
测试代码
using Moq; namespace ConsoleAppBastelProjekt.UnitTests; [TestClass] public sealed class Test1 { [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); } }
抛出的错误信息
System.NullReferenceException
HResult=0x80004003
Message = Object reference not set to an instance of an object.
Source = ConsoleAppBastelProjekt.UnitTests
Stacktrace: bei ConsoleAppBastelProjekt.UnitTests.Test1.d__0.MoveNext() in D:\Git\ForeignRepos\ConsoleAppBastelProjekt\ConsoleAppBastelProjekt.UnitTests\Test1.cs: Zeile16
有没有大佬能帮忙判断下这是Moq的bug,还是我使用RaiseAsync的姿势不对?麻烦指点一下,谢谢!
内容来源于stack exchange

