事件模块—-NSubstitute事件处理完全教程:轻松管理.NET事件模拟 - 处理Action类型的事件同样简单:
NSubstitute事件处理完全教程:轻松管理.NET事件模拟
【免费下载链接】NSubstitute A friendly substitute for .NET mocking libraries. 项目地址: https://gitcode.com/gh_mirrors/ns/NSubstitute
NSubstitute是一个友好的.NET模拟库替代品,专门为简化单元测试中的事件处理而设计。无论你是刚开始接触单元测试的新手,还是有经验的.NET开发者,掌握NSubstitute的事件处理能力都能让你的测试代码更加简洁高效。
什么是NSubstitute事件模拟? 拼多多帮助力入口
在.NET单元测试中,事件处理是一个常见但复杂的场景。传统的模拟库在处理事件时往往需要大量样板代码,而NSubstitute通过直观的语法让事件模拟变得异常简单。
基础事件触发方法
简单事件触发
对于标准的EventHandler事件,NSubstitute可以自动创建所有必要的参数:
var engine = Substitute.For();
bool wasCalled = false;
engine.Idling += (sender, args) => wasCalled = true;
// 触发事件
engine.Idling += Raise.Event();
Assert.That(wasCalled, Is.True);
自定义参数的事件触发
当事件参数没有默认构造函数时,你可以手动提供参数:
engine.LowFuelWarning += (sender, args) => numberOfEvents++;
// 使用特定参数触发事件
engine.LowFuelWarning += Raise.EventWith(new LowFuelWarningEventArgs(10));
Assert.That(numberOfEvents, Is.EqualTo(1));
高级事件处理技巧
处理委托事件
对于使用自定义委托的事件,NSubstitute同样支持:
var notifySub = Substitute.For();
bool propertyChangedCalled = false;
notifySub.PropertyChanged += (sender, args) => propertyChangedCalled = true;
notifySub.PropertyChanged += Raise.Event(
this, new PropertyChangedEventArgs("TestProperty"));
Assert.That(propertyChangedCalled, Is.True);
Action类型事件
处理Action类型的事件同样简单:
int actualRpm = 0;
engine.RevvedAt += rpm => actualRpm = rpm;
engine.RevvedAt += Raise.Event>(123);Assert.That(actualRpm, Is.EqualTo(123));
实际应用场景
测试事件订阅者
NSubstitute让你能够轻松验证事件订阅者是否正确响应:
// 模拟事件源
var eventSource = Substitute.For();
var eventHandler = Substitute.For();
// 设置事件处理
eventSource.SomeEvent += eventHandler.HandleEvent;
// 触发事件并验证处理逻辑
eventSource.SomeEvent += Raise.Event();
eventHandler.Received().HandleEvent(Arg.Any