【问题标题】:Setting a passed parameter to a specific value in Moq将传递的参数设置为 Moq 中的特定值
【发布时间】: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);
  }

portISerialPort 的一个实例。

我正在尝试为 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


    【解决方案1】:

    您可以使用Callback 方法访问传入的参数并设置传入缓冲区的第一个元素:

    mock.Setup(m => m.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))
        .Returns(3)
        .Callback<byte[], int, int>((buffer, offset, count) => { buffer[0] = 0x07; });
    

    你可以在Returns里面做同样的事情

    mock.Setup(m => m.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))
        .Returns<byte[], int, int>((buffer, offset, count) =>
        {
            buffer[0] = 0x07;
            return 3;
        });
    

    但是使用Callback 比在Returns 中产生副作用更容易理解

    【讨论】:

      【解决方案2】:

      为了跟进@nemesv 的回答,编译器不喜欢我的回调方法中的泛型参数,所以我不得不使用 lambda 中的类型。

      mock.Setup(m => m.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))
      .Callback((byte[] buffer, int offset, int count) => {}).Returns(3);
      

      【讨论】:

        猜你喜欢
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多