c# - 如何模拟 SerialDataReceivedEventArgs

标签 c# unit-testing moq mstest

我有一个外设驱动程序,它使用串口与外设进行通信。我想对该驱动程序进行单元测试并尝试模拟串口。因此,我为框架类型 SerialPort 创建了一个包装器,让它实现一个接口(interface):

public interface IScannerPort
{
    Handshake Handshake { get; set; }
    bool IsOpen { get; }

    event SerialDataReceivedEventHandler DataReceived;

    void Close( );
    void Open( );
    string ReadLine( );
}

现在我使用最小起订量创建了一个模拟:

Mock<IScannerPort> scannerPort = new Mock<IScannerPort>( );

然后我想引发 DataReceived 事件。但是 SerialDataReceivedEventArgs 不允许我设置 EventType 属性。所以我也尝试模拟 SerialDataReceivedEventArgs,结果是

Mock<SerialDataReceivedEventArgs> args = new Mock<SerialDataReceivedEventArgs>();
args.SetupProperty(a => a.EventType, SerialData.Eof);

但是第二行引发了一个 NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: a => a.EventType

我怎样才能发起这个事件?或者我如何模拟事件参数?

最佳答案

不一定要模拟 SerialDataReceivedEventArgs。可以使用反射创建它的一个实例:

ConstructorInfo constructor = typeof (SerialDataReceivedEventArgs).GetConstructor(
    BindingFlags.NonPublic | BindingFlags.Instance,
    null,
    new[] {typeof (SerialData)},
    null);

SerialDataReceivedEventArgs eventArgs = 
    (SerialDataReceivedEventArgs)constructor.Invoke(new object[] {SerialData.Eof});

然后可以使用 vent args 的“真实”实例在模拟实例上引发事件:

scannerPort.Raise( s => s.DataReceived += null, eventArgs );

关于c# - 如何模拟 SerialDataReceivedEventArgs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582087/

相关文章:

c# - 在 BAL 类逻辑方面需要帮助

unit-testing - 如何在 Jasmine 测试中模拟 Angular $resource

visual-studio - VS08 中无法加载测试项目

c# - 使用 Moq 确定方法是否被调用

c# - 当代码验证它收到的类型时,如何使用模拟

c# - Moq 使用 ReturnsAsync 并修改 It.IsAny 输入参数

c# - System.Runtime.InteropServices.COMException (0x80040154) :

c# - 有没有办法使 row.DefaultCellStyle.BackColor 固定,尽管重新绘制?

c# - 如何将 C dll 加载到 C# 代码中?

java - 使用 Maven 运行单个测试方法