使用 Moq 模拟方法数组参数
Mock a method array argument using Moq
使用 Moq4,我试图用 List<string>
替换方法的参数之一。但是,使用 byte[]
类型,我无法更改该值。 有什么想法或解决方案吗?
代码
public class SomeObject
{
public virtual void DoSomething(byte[] array, int offset, int count) { }
}
[Fact]
public void SomeTest()
{
// Arrange
byte[] expectedArray = new byte[] { 5, 6, 7, 8, 9 };
var mock = new Mock<SomeObject>();
mock.Setup(so => so.DoSomething(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))
.Callback<byte[], int, int>(
(buffer, offset, count) => { buffer = new byte[] { 5, 6, 7, 8, 9 }; }
);
var target = mock.Object;
var array = new byte[64];
// Act
target.DoSomething(array, 0, 10);
// Assert
Assert.Equal(expectedArray, array);
}
获得输出
Message:
Assert.Equal() Failure
Expected: Byte[] [5, 6, 7, 8, 9]
Actual: Byte[] [0, 0, 0, 0, 0, ...]
将 new byte[] { 5, 6, 7, 8, 9 };
分配给 lambda 参数会创建一个 new
对象,这与您之前创建的原始 byte[64]
不同。
您的 lambda 可以修改通过引用传递的值的唯一方法是 使用 该引用,而不是替换它。即:buffer[0] = 5
.
如果 SomeObject
是您自己的代码(并且您不应该模拟您不拥有的代码),请考虑 returns 数组的签名相反,符合 CQS。在这种情况下,您可以只使用 .Returns()
。
使用 Moq4,我试图用 List<string>
byte[]
类型,我无法更改该值。 有什么想法或解决方案吗?
代码
public class SomeObject { public virtual void DoSomething(byte[] array, int offset, int count) { } } [Fact] public void SomeTest() { // Arrange byte[] expectedArray = new byte[] { 5, 6, 7, 8, 9 }; var mock = new Mock<SomeObject>(); mock.Setup(so => so.DoSomething(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())) .Callback<byte[], int, int>( (buffer, offset, count) => { buffer = new byte[] { 5, 6, 7, 8, 9 }; } ); var target = mock.Object; var array = new byte[64]; // Act target.DoSomething(array, 0, 10); // Assert Assert.Equal(expectedArray, array); }
获得输出
Message: Assert.Equal() Failure Expected: Byte[] [5, 6, 7, 8, 9] Actual: Byte[] [0, 0, 0, 0, 0, ...]
将 new byte[] { 5, 6, 7, 8, 9 };
分配给 lambda 参数会创建一个 new
对象,这与您之前创建的原始 byte[64]
不同。
您的 lambda 可以修改通过引用传递的值的唯一方法是 使用 该引用,而不是替换它。即:buffer[0] = 5
.
如果 SomeObject
是您自己的代码(并且您不应该模拟您不拥有的代码),请考虑 returns 数组的签名相反,符合 CQS。在这种情况下,您可以只使用 .Returns()
。