Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use Mocking and Fakes under .NET Core 1.1 or higher?

Tags:

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?

like image 713
Daan Avatar asked Apr 28 '17 20:04

Daan


People also ask

Are fakes better than Mocks?

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.

What is mock test in .NET core?

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.

What is the difference between mocks stubs and fakes?

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.


1 Answers

  1. Install "Moq" using nuget
  2. Create unit-test using NUnit or similar
  3. 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()); 
like image 169
Dzianis Yafimau Avatar answered Oct 29 '22 07:10

Dzianis Yafimau