Skip to content

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:

xml
<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:

c#
var mock = new Mock<IFoo>();

NSubstitute:

c#
var substitute = Substitute.For<IFoo>();

Setting up a method call

Moq:

c#
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

NSubstitute:

c#
substitute.DoSomething("ping").Returns(true);

Verifying a method call

Moq:

c#
mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce());

NSubstitute:

c#
substitute.Received().DoSomething("ping");

Setting up a property

Moq:

c#
mock.Setup(foo => foo.Name).Returns("John Doe");

NSubstitute:

c#
substitute.Name.Returns("John Doe");

Handling arguments

Moq:

c#
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);

NSubstitute:

c#
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

NSubstitute Documentation

NSubstitute Quickstart

NSubstitute Cheat Sheet

Was this page helpful?

Happy React is loading...