I have been using .NET Framework 4.X for years and I just switched to .NET Core . Since I want to do TDD, I want to use a mocking framework and microsoft fakes. However, it is not clear to me how to do that for .NET Core since the classical solutions are not supported.
Can someone tell me how I should use Mocking and Fakes under .NET Core 1.1?
Fakes are generally used to improve performance by avoiding external calls. Mocks are used to verify the behavior of our code. Stubs are used to provide data that our code needs to run. We should use the simplest test double that will get the job done.
A mock version of something is an object that can act like the real thing but can be controlled in test code. Moq (pronounced “mok u” or “mock”) is a library available on NuGet that allows mock objects to be created in test code and it also supports . NET Core.
Stub - an object that provides predefined answers to method calls. Mock - an object on which you set expectations. Fake - an object with limited capabilities (for the purposes of testing), e.g. a fake web service. Test Double is the general term for stubs, mocks and fakes.
Write something like this:
// Arrange var mock = new Mock<IRepository>(); mock.Setup(repo=>repo.GetAll()).Returns(GetTestPhones()); var controller = new HomeController(mock.Object); // Act var result = controller.Index(); // Assert var viewResult = Assert.IsType<ViewResult>(result); var model = Assert.IsAssignableFrom<IEnumerable<Phone>>(viewResult.Model); Assert.Equal(GetTestPhones().Count, model.Count());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With