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 »

C#.NET - day 08

Day 08 : Unit Testing — The Real Reason Interfaces Exist Proving service behavior without repositories or databases Introduction Many tutorials introduce inter...

MiniScript Road Map for 2026

2026 Outlook With 2025 coming to a close, it’s time to look ahead to 2026! MiniScript is now eight years old. Many programming languages really come into their...