应如何为 "send-receive" 方法编写单元测试?



如何为在 or ther 中执行发送-接收操作以与通用设备通信的方法编写单元测试?

在下面的示例中,为了查询串行设备(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...
    }
    ...
}

另一个疑问:编写测试只是为了检查是否应该使用特定参数调用方法是否正确?

这是"单元测试"此类设备的好方法。除非您要连接真实设备或模拟设备。

您应该保持每个测试简单明了 - 即在测试时读取返回预期的字符串(而不是其他字符串)并检查系统行为,在写入时验证是否使用确切的字符串调用了写入。

最新更新