Saturday, May 26, 2018

I finally figured out how to do mocking with Moq in .NET Core!

The process:

    • In Visual Studio 2017 go to: Tools > Extensions and Updates...
    • Pick "Online" at the left.
    • Searching for "xUnit" at the upper right should find "xUnit Test Item Template"
    • Install it.
    • create a new xUnit Test Project (.NET Core) and be sure it is .NET Core and not .NET Framework
    • go to: Tools > NuGet Package Manager > Manage NuGet Packages for Solution...
    • Search for "xunit" across the top by: Browse, Installed, Updates, and Consolidate
    • I installed xunit.runner.console, xunit, and xunit.analyzers all three!
    • Search for "moq" and install Moq next!
    • add a reference to the .NET Core project you wish to test
    • write some tests!
    • run tests at: Test > Run > All Tests


Here is a class I tested.

namespace MockingBird
   public static class StaticMagic
      public static string AddSix(int value, ICalculator calculator)
         return value + " + 6 = " + calculator.Add(value,6);


Here is the interface I used in the class I tested.

namespace MockingBird
   public interface ICalculator
      int Add(int yin, int yang);
      int Subtract(int yin, int yang);v    }


Here is the test I wrote.

using MockingBird;
using Xunit;
using Moq;
namespace MyTests
   public class UnitTest1
      public void Test1()
         Mock<ICalculator> calculator = new Mock<ICalculator>();
         calculator.Setup(c => c.Add(It.IsAny<int>(), It.IsAny<int>())).Returns(9);
         string calculation = StaticMagic.AddSix(3, calculator.Object);
         Assert.Equal(calculation, "3 + 6 = 9");


I got turned around to go the right direction on this stuff after looking at a PluralSight training by a Jason Roberts on the subject. He said some interesting things along the way such as naming a variable sut and explaining that it stood for "System Under Test." He lists the four test doubles as Fakes, Dummies, Stubs, and Mocks instead of Spies, Dummies, Stubs and Mocks, and suggests that Moq can facilitate Dummies, Stubs, and Mocks. He suggests that Fakes are implementations of interfaces that are actually wired up to do things like talk to a predictable staged database such as the EF (Entity Framework) Core in-memory provider in lieu of a production database.

No comments:

Post a Comment