【发布时间】:2021-06-18 10:45:00
【问题描述】:
5-cent 版本:如何手动触发 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);
}
}
}
目前我不允许发布更多代码,所以如果提供的信息不充分,请提供一些您认为与情况相关的链接,我会尝试从而是在那里。
感谢您的阅读。
【问题讨论】: