unit-testingasp.net-coremockingmicrosoft-fakes

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


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?


Solution

    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());