使用Fluent Assertions事件监控时触发System.InvalidProgramException异常
使用Fluent Assertions事件监控触发InvalidProgramException异常
我在单元测试中尝试使用Fluent Assertions的事件监控功能,但执行测试时触发了奇怪的System.InvalidProgramException异常。
异常信息
Message: System.InvalidProgramException : Common Language Runtime detected an invalid program. Stack Trace: Func`2DynamicHandler(EventRecorder , InternalOrder ) EventExtensions.Raise[T](Func`2 handlers, T arg) line 42 InternalOrderProcessor.CreateInternalOrder(SkuDemand skuDemand, PickLevelDestinationStateInfo pickLevelDestinationStateInfo) line 199 InternalOrderProcessor.CreateInternalOrders(IList`1 skuDemands, PickLevelDestinationStateInfo pickLevelDestinationStateInfo) line 86 InternalOrderProcessorTests.CreateInternalOrder_MultiDemandCoveredWithOneSku_OrderForOneSkuCreatedAndSent() GenericAdapter`1.GetResult() AsyncToSyncAdapter.Await(Func`1 invoke) TestMethodCommand.RunTestMethod(TestExecutionContext context) TestMethodCommand.Execute(TestExecutionContext context) <>c__DisplayClass1_0.<Execute>b__0() DelegatingTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
触发异常的测试代码
var monitor = this.service.Monitor(); await this.service.CreateOrder(); // 异常触发点 monitor.Should().Raise(nameof(this.service.OrderCreated));
正常工作的手动绑定方式
var isRaised = false; this.service.OrderCreated += order => { isRaised = true; return Task.CompletedTask; }; await this.service.CreateOrder(); // 无异常 isRaised.Should().BeTrue();
解决建议
- 升级Fluent Assertions版本:该异常大概率是旧版本对异步事件的动态代理生成bug导致的,更新到最新稳定版即可解决。
- 排查工具冲突:如果测试中用到了代码覆盖率、AOP拦截类工具,这类工具可能干扰Fluent Assertions的动态代码生成逻辑,暂时禁用后再测试。
- 检查事件委托类型:确保
OrderCreated事件的委托是标准异步类型(比如Func<T, Task>),非标准委托可能导致Fluent Assertions无法正确生成监控代理。
内容的提问来源于stack exchange,提问作者Артур Малюга
相关产品推荐
相关产品推荐

