How to Mock Public Methods in C# with NSubstitute
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.