Migrating from Moq to NSubstitute
This guide will help you migrate from Moq to NSubstitute, a lightweight mocking library for .NET. This is as a result of privacy concerns identified in the Moq Library.
Step 1: Install NSubstitute
To get started, you'll need to install the NSubstitute NuGet package. You can do this using the Package Manager Console in Visual Studio or by adding the following line to your project file:
<PackageReference Include="NSubstitute" Version="5.0.0" />
Step 2: Replace Moq with NSubstitute
Once you've installed NSubstitute, you can start replacing your Moq code with NSubstitute code. Here are some examples of how to do this:
Creating a mock object
Moq:
var mock = new Mock<IFoo>();
NSubstitute:
var substitute = Substitute.For<IFoo>();
Setting up a method call
Moq:
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);
NSubstitute:
substitute.DoSomething("ping").Returns(true);
Verifying a method call
Moq:
mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce());
NSubstitute:
substitute.Received().DoSomething("ping");
Setting up a property
Moq:
mock.Setup(foo => foo.Name).Returns("John Doe");
NSubstitute:
substitute.Name.Returns("John Doe");
Handling arguments
Moq:
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
NSubstitute:
substitute.DoSomething(Arg.Any<string>()).Returns(true);
Step 3: Run your tests
Once you've replaced your Moq code with NSubstitute code, you should run your tests to make sure everything is working as expected.
Conclusion
Migrating from Moq to NSubstitute is a straightforward process that can help you write more concise and readable tests. By following the steps outlined in this guide, you should be able to migrate your code with minimal effort.
Further Reading
Was this page helpful?
CHAT SAMMIAT