【发布时间】:2016-01-20 15:30:26
【问题描述】:
应该如何为执行发送-接收操作以与通用设备通信的方法编写单元测试?
在以下示例中,为了查询串行设备(MyDevice.Read 方法),将以特定方式格式化的字符串发送到设备,设备根据发送的消息以特定字符串响应。
这是模拟串口所需的接口:
public interface ISerialPort
{
void WriteLine(string text);
void ReadLine(string text);
}
这是使用该接口的客户端类:
public class MyDevice
{
private ISerialPort _port;
public MyDevice(ISerialPort port)
{
_port = port;
}
public DeviceResponse Read(...)
{
_port.WriteLine(...);
string response = _port.ReadLine();
// Parse the response.
return new DeviceResponse(response);
}
}
这是我要编写的 Read 方法的单元测试(故意省略了失败/异常测试):
[TestClass]
public class MyDeviceTests
{
[TestMethod]
public void Read_CheckWriteLineIsCalledWithAppropriateString()
{
Mock<ISerialPort> port = new Mock<ISerialPort>();
MyDevice device = new MyDevice(port.Object);
device.Read(...);
port.Verify(p => p.WriteLine("SpecificString"));
}
[TestMethod]
public void Read_DeviceRespondsCorrectly()
{
Mock<ISerialPort> port = new Mock<ISerialPort>();
MyDevice device = new MyDevice(port.Object);
port.Setup(p => p.ReadLine()).Returns("SomeStringFromDevice");
DeviceResponse response = device.Read(...);
// Asserts here...
}
...
}
另一个疑问:编写测试只是为了检查是否应该使用特定参数调用方法是否正确?
【问题讨论】:
-
我不是 100% 确定我理解了这个问题,但我认为您必须在模拟串行端口中编写代码,以便它会以一组给定的响应响应一组请求。也许
Dictionary的响应以请求为键?这是您的查询吗?
标签: c# unit-testing io moq device-driver