loading...

Moq and how creating Mocks with Linq

andreslozadamosto profile image Andres Lozada Mosto ・1 min read

There is a not so known feature in Moq library and is the possibility to create our Mocks with Linq.

Benefit to use Linq to create our mocks:

  • Remove boilerplate code
  • Removing Setup()call for each member we want configurate
  • Remove calling .Object when we use the object mocked
  • We still able to Verify our mocks

So, let’s see an example 😎

Simple & hierarchy/recursive properties

var id = 32;
var username = "Andres";
var street = "14th Street NW";

var userModel = Mock.Of<IUserModel>(user =>
    user.Id == id &&
    user.Username == username &&
    user.Address.Street == street
);
Enter fullscreen mode Exit fullscreen mode

Methods with any parameter matching

var userModel = Mock.Of<IUserModel>();
var userList = Fixture
    .Build<UserModel>()
    .With(x => x.Address, Fixture.Create<Address>())
    .CreateMany(10).ToList<IUserModel>();

var repository = Mock.Of<IRepository>(x =>
    x.Add(It.IsAny<IUserModel>()) == true &&
    x.Add(userModel) == false &&
    x.ActiveUsers() == userList
);
Enter fullscreen mode Exit fullscreen mode

Verify methods

var userAdded = repository.Add(Mock.Of<IUserModel>());

var mock = Mock.Get(repository);

mock.Verify(user => user.Add(It.IsAny<IUserModel>()), Times.Once);
Enter fullscreen mode Exit fullscreen mode

What do you think? will you start using Linq to write your Mocks?

Fell free to share your thoughts on the comments 😎 πŸ’ͺ

Discussion

pic
Editor guide