【问题标题】:How should unit tests be written for a "send-receive" method?应该如何为“发送-接收”方法编写单元测试?
【发布时间】: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


【解决方案1】:

这是对此类设备进行“单元测试”的好方法。除非您想连接真实设备或模拟设备。

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

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2019-06-12
    • 2020-06-30
    • 1970-01-01
    相关资源
    最近更新 更多