DEV Community

Andres Lozada Mosto
Andres Lozada Mosto

Posted on

Moq and how creating Mocks with Linq

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 😎 💪

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay