简体   繁体   English

如何在Moq中使用lambda语法设置现有的模拟?

[英]How to set up an existing mock using lambda syntax in Moq?

There is a new syntax in Moq that allows me to create a mock from scratch using Moq中有一种新语法允许我从头开始创建一个模拟

var newMock = Mock.Of<IInterface>(m => m.GetSomeValue() == value);

Sometimes I don't create the mock myself (eg when using AutoData Theories ). 有时我自己不创建模拟(例如使用AutoData理论时 )。 Then I have to set up the mock using the older syntax 然后我必须使用旧语法设置模拟

existingMock.Setup(m => m.GetSomeValue()).Returns(value);

I don't like this for two reasons 我不喜欢这个有两个原因

  1. It's less readable (imho) 它的可读性较差(imho)
  2. It forces me to mix old and new syntax. 它迫使我混合使用新旧语法。

I would prefer to set up an existing mock using something like 我宁愿用类似的东西设置一个现有的模拟

existingMock.SetupUsingNewSyntax(m => m.GetSomeValue() == value);
  • Is this possible? 这可能吗?
  • If no, is it on the roadmap? 如果不是,是否在路线图上?
    I would assume the new syntax to be introduced for existing mocks as well. 我会假设为现有的模拟引入新的语法。
  • If no, how could I implement this myself? 如果不是,我怎么能自己实现呢?

I already know how to use Mock.Get<>() and Mock.Of<>() , and how the mocks and mock objects are related. 我已经知道如何使用Mock.Get<>()Mock.Of<>() ,以及模拟和模拟对象是如何相关的。

Moq also is the first and only framework so far to provide Linq to Mocks, so that the same behavior above can be achieved much more succintly Moq也是迄今为止第一个也是唯一一个为Linq提供Mocks的框架,因此可以更加轻松地实现上述相同的行为。

Since there are now two ways to create and setup a new mock, the old way and the new succint way, I was hoping it would carry over and also include setting up existing mocks. 由于现在有两种方法来创建和设置一个新的模拟,旧的方式和新的succint方式,我希望它会延续并包括设置现有的模拟。

I have uploaded the solution code to my Gist . 我已将解决方案代码上传到我的Gist In brief, the gist code has just removed the logic to create a mocked instanc from the original code. 简而言之,gist代码刚刚删除了从原始代码创建模拟instanc的逻辑。 To do so, I need to access to the MockQueryable<T> class which is internal class, so I used the .NET reflection. 为此,我需要访问内部类的MockQueryable<T>类,因此我使用了.NET反射。

To avoid the reflection code, you can copy the code of MockQueryable<T> from Moq source to your test code, as well as some internal types related with MockQueryable<T> if needed. 要避免使用反射代码,可以将MockQueryable<T>的代码从Moq源代码复制到测试代码,以及一些与MockQueryable<T>相关的内部类型MockQueryable<T>如果需要)。

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

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