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
Setup()call for each member we want configurate
- Remove calling
.Objectwhen we use the object mocked
- We still able to Verify our mocks
So, let’s see an example 😎
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 );
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 );
var userAdded = repository.Add(Mock.Of<IUserModel>()); var mock = Mock.Get(repository); mock.Verify(user => user.Add(It.IsAny<IUserModel>()), Times.Once);
What do you think? will you start using Linq to write your Mocks?
Fell free to share your thoughts on the comments 😎 💪