Moq - Get Setup() to return a dynamic collection from a fake repository
Use Moq lazy loading to return an updated collection from the Setup() method, it's as easy as changing the argument to the Setup().Returns() method from an object to a lambda expression.
So if you've got this:
_mockUserRepository.Setup(x => x.GetAll()).Returns(FakeUserData.Users);
Just change it to this:
_mockUserRepository.Setup(x => x.GetAll()).Returns(() => FakeUserData.Users);
If you are using this approach you also need to remember to reset your fake data at the beginning of each test, I do this with a simple static reset method on my fake data class.
class FakeUserData
{
public static void Reset()
{
_users = null;
}
...
}
Which is called before each test with the following setup method (using MSTest):
[TestInitialize]
public void Setup()
{
FakeUserData.Reset();
...
}
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some ASP.NET Help?
Search fiverr to find help quickly from experienced ASP.NET developers.