[英]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.