简体   繁体   English

使用Moq在C#中进行验证

[英]Using Moq to verify in C#

I'm trying to mock a database so that I can verify that the save method was called. 我正在尝试模拟数据库,以便可以验证是否调用了save方法。 I have a project which saves to a database, it takes a list of the objects to save, and a connection string. 我有一个保存到数据库的项目,它包含要保存的对象的列表以及一个连接字符串。

this._database.Save<Constraint>(constraints, "DEFAULT");

When I debug I can see that the test successfully goes into my project with a mocked database, and that it hits the save line exactly once. 当我调试时,我可以看到测试成功地将模拟数据库输入到我的项目中,并且它仅命中一次保存行。

In my test project I create an instance of the class calling the save method, create and create a mock database, and use .Setup for the save method. 在我的测试项目中,我创建了一个调用save方法的类的实例,创建并创建了一个模拟数据库,并将.Setup用作save方法。

private Mock<IDatabase> _mockDatabase;
...
_mockDatabase = new Mock<IDatabase>();
_mockDatabase.Setup(d => d.Save<Types.Constraint>(It.IsAny<Types.Constraint>(), It.IsAny<String>()));

Then in my test method, I call .Verify to make sure that save was called one time. 然后,在我的测试方法中,我调用.Verify以确保一次调用了save。

_mockDatabase.Verify(d => d.Save<Constraint>(It.IsAny<Constraint>(), It.IsAny<String>()), Times.Once);

However the test fails on this verify. 但是,此验证测试失败。 Does anyone know how I can fix this? 有谁知道我该如何解决? Thanks for any help/ideas! 感谢您的帮助/想法!

Moq.MockException: Moq.MockException:
Expected invocation on the mock once, but was 0 times: d => d.Save(It.IsAny(), It.IsAny()) 预期对模拟进行一次调用,但是被调用0次:d => d.Save(It.IsAny(),It.IsAny())

Configured setups: 配置的设置:
d => d.Save(It.IsAny(), It.IsAny()), Times.Never d => d.Save(It.IsAny(),It.IsAny()),Times.Never

Performed invocations: 执行的调用:
IDatabase.Save(System.Collections.Generic.List`1[Types.Constraint], "DEFAULT") IDatabase.Save(System.Collections.Generic.List`1 [Types.Constraint],“ DEFAULT”)

With your code, what you sending is a List<Constraint> and you are expecting is a Constraint so: 使用您的代码,您发送的是List<Constraint>而您期望的是一个Constraint因此:

Change the setup to : 将设置更改为:

_mockDatabase.Setup(d => d.Save<Constraint>(It.IsAny<List<Constraint>>(), It.IsAny<String>()));

and Verify to : 并验证以:

_mockDatabase.Verify(d => d.Save<Constraint>(It.IsAny<List<Constraint>>(), It.IsAny<String>()), Times.Once);

It is calling the save method with a List<Constraint> instead of just Constraint , that's why it's failing. 它调用一个保存方法List<Constraint> ,而不是仅仅Constraint ,这就是为什么它的失败。 You can either change the expected input or verify your code before calling the Save 您可以更改预期的输入或验证代码,然后再调用Save

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM