Moq调用参数在后续调用中更改



在下面的例子中,我有一个简单的Service类,它用它的输入和一个处理器调用Service. doservice()两次,传递相同的InputParameters对象,首先x = 5,然后x = 100;问题是,在单元测试中,我想检查DoService()方法是否用原始值(x==5)调用一次,用新值(x==100)调用一次,但显然它被x==100调用两次

public class InputParameters
{
public int x, y;
}
public interface IService
{
bool DoSomething(InputParameters input);
}
public class Service : IService
{
public bool DoSomething(InputParameters input)
{
return input.x > input.y;
}
}
public class Processor
{
public IService _service;
public Processor(IService theServive)
{
_service = theServive;
}
public void Process()
{
InputParameters input = new InputParameters();
input.x = 5;
input.y = 50;
_service.DoSomething(input);
input.x = 100;
_service.DoSomething(input);
}

和测试

private Mock<IService> _serviceMock;
private Processor _processor;
[SetUp]
public void Setup()
{
_serviceMock = new Mock<IService>();
_processor = new Processor(_serviceMock.Object);
}
[Test]
public void Test()
{
_serviceMock.Setup(service => service.DoSomething(
It.IsAny<InputParameters>()
)).Returns(() => false);
_processor.Process();
_serviceMock.Verify(service => service.DoSomething(
It.Is<InputParameters>(input => input.x == 5)
), Times.Exactly(1)); //returns 0 times called
_serviceMock.Verify(service => service.DoSomething(
It.Is<InputParameters>(input => input.x == 100)
), Times.Exactly(1)); //return 2 times calledd

我已经调试了执行,我可以看到当我调用input时,第一个调用参数被改变了。x = 100,我不明白Moq如何保持对调用参数的引用?

我也尝试了不同的设置,结果相同:

_serviceMock.Setup(service => service.DoSomething(
It.Is<InputParameters>(input => input.x == 5)
)).Returns(() => true);
_serviceMock.Setup(service => service.DoSomething(
It.Is<InputParameters>(input => input.x == 100)
)).Returns(() => false);

代码可以在这里找到:https://github.com/rufusz/MoqInvocationCountIssue

我从Moq收到了正式的回答:如果参数是ref类型,那么这是预期的行为。如果它是值类型,则在存储调用参数时将其复制到内存中,但这对于ref类型是不可能的,例如文件句柄或窗口句柄可能会产生问题,或者根本无法(深度)克隆。

最新更新