سؤال

There is a new syntax in Moq that allows me to create a mock from scratch using

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

Sometimes I don't create the mock myself (e.g. when using AutoData Theories). 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)
  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.

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

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.

هل كانت مفيدة؟

المحلول

I have uploaded the solution code to my Gist. In brief, the gist code has just removed the logic to create a mocked instanc from the original code. To do so, I need to access to the MockQueryable<T> class which is internal class, so I used the .NET reflection.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top