[英]How to trigger DataReceivedEventHandler?
5 美分版本:如何手动触发 DataReceivedEventHandler? 我记得使用异步延迟委托来触发它,但我不知道如何。
5 美元版本:我目前正在对我的一个项目进行单元测试,并且我目前正在尝试模拟成功的通信事件。 测试方法如下。
public async Task<CommandResponse> StartScanAsync()
{
if (_isCommandInProgress)
{
Trace.WriteLine("Command in progress.");
return new CommandResponse(CommandStatus.CommandInProgress);
}
else
{
Task<DongleResponse> t = WaitForDongleResponse(CommandId.CMD_START);
byte[] sendBuf = { 0x00 };
_serialDriver.send(sendBuf, 1);
Trace.WriteLine("Command send. Waiting for response");
// Wait for either dongle response or timeout
// If dongleResponse comes first, set
if (await Task.WhenAny(t, Task.Delay(RECEIVE_TIMEOUT)) == t) {
_isScanning = true;
_isCommandInProgress = false;
return new CommandResponse(CommandStatus.OK, t.Result);
}
else
{
_isCommandInProgress = false;
_rspRxTcs.SetCanceled();
return new CommandResponse(CommandStatus.ResponseTimeout);
}
}
}
下面是我的单元测试代码
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using FluentAssertions;
using System.Threading.Tasks;
namespace TriggerDataHandler.Tests
{// SUCCESSFULLY TRIGGER TIMEOUT AND SUCCESS PROMPTS
[TestClass()]
public class CommandServiceTestClass
{
private readonly Mock<ISerialDriver> MockDriver
= new Mock<ISerialDriver>();
[TestMethod()]
public async Task StartScan_And_ReturnSUCCESS()
//How to trigger dataHandler? return 0x0000
{
//Arrange: Set up variables for Act to work
CommandService csGO = new CommandService(MockDriver.Object);
//Act: Initiate StartScan and wait for a timeout to occur
CommandResponse result = await csGO.StartScanAsync();
//Assert: Your end goal which should be true
Assert.AreEqual(result.Status, CommandStatus.OK);
}
}
}
我目前不允许发布更多代码,因此如果提供的信息不足,请提供一些您认为与情况相关的链接,我将尝试从那里开始工作。
感谢阅读顺便说一句。
忽略 5 美元的位。 在测试上下文中,确保您选择的事件处理程序同时具有 Object 和 EventArgs 要求,安装 MoQ,并对 Mocked 目标使用 Raise 命令。
我的例子
Task<CommandResponse> startScanTask = csGO.StartScanAsync();
await Task.Delay(500);
MockDriver.Raise(x => x.Received += null, new DataReceivedEventArgs { buffer, length} );
其中 x 是指用于制作接口的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.