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
);
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
);
Verify methods
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 😎 💪
Top comments (0)