How to Mock Public Methods in C# with NSubstitute

Published: (January 5, 2026 at 09:30 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Make the method virtual

This is the minimal change and fully supported by NSubstitute.

public class ProductService
{
    public virtual int GetPrice()
    {
        return 1;
    }
}

var service = Substitute.For<ProductService>();
service.GetPrice().Returns(42);

Extract an interface (cleanest design)

This is the best option.

public interface IProductService
{
    int GetPrice();
}

Inject the interface and mock it instead:

var service = Substitute.For<IProductService>();
service.GetPrice().Returns(42);

Use a wrapper / adapter (for third‑party or legacy code)

public interface IProductServiceWrapper
{
    int GetPrice();
}

public class ProductServiceWrapper : IProductServiceWrapper
{
    private readonly ProductService _service;
    public int GetPrice() => _service.GetPrice();
}

Mock ProductServiceWrapper in the same way as the interface.

Back to Blog

Related posts

Read more »

LLVM: The Bad Parts

Article URL: https://www.npopov.com/2026/01/11/LLVM-The-bad-parts.html Comments URL: https://news.ycombinator.com/item?id=46588837 Points: 14 Comments: 0...