【发布时间】:2015-06-06 13:49:28
【问题描述】:
我正在对一个通过串行端口与硬件设备通信的类进行单元测试。我创建了一个接口来隔离 System.IO 中的SerialPort 类:
public interface ISerialPort
{
String PortName { get; set; }
bool IsOpen { get; }
void Open();
void Close();
int Read(byte[] buffer, int offset, int count);
void Write(byte[] buffer, int offset, int count);
}
在我的测试类中有一个函数调用Read,并检查特定值。例如:
public bool IsDevicePresent()
{
byte[] buffer = new byte[3];
int count = 0;
try
{
port.Write(new byte[] { 0x5A, 0x01 }, 0, 2);
count = port.Read(buffer, 0, 3);
}
catch (TimeoutException)
{
return false;
}
return (buffer[0] == 0x07 && count == 3);
}
port 是ISerialPort 的一个实例。
我正在尝试为 IsDevicePresent 函数编写一些测试,使用 Moq 来模拟 ISerialPort。但是,我不知道如何让 Moq 在传递的字节数组 (buffer) 中设置值。我可以让 Moq 返回 3,但是如何让 Moq 将 buffer 中的第一个字节设置为 0x07?
var mock = new Mock<ISerialPort>();
mock.Setup(m => m.Read(It.IsAny<byte[]>(), It.IsAny<int>(),It.IsAny<int>()))
.Returns(3);
【问题讨论】:
标签: c# unit-testing moq