如何使用 NSubstitute 对 C# 公共方法进行 Mock
发布: (2026年1月6日 GMT+8 10:30)
1 min read
原文: Dev.to
Source: Dev.to
将方法设为 virtual
这是最小的改动,并且完全受 NSubstitute 支持。
public class ProductService
{
public virtual int GetPrice()
{
return 1;
}
}
var service = Substitute.For<ProductService>();
service.GetPrice().Returns(42);
提取接口(最清晰的设计)
这是最佳方案。
public interface IProductService
{
int GetPrice();
}
注入接口并对其进行模拟:
var service = Substitute.For<IProductService>();
service.GetPrice().Returns(42);
使用包装器 / 适配器(用于第三方或遗留代码)
public interface IProductServiceWrapper
{
int GetPrice();
}
public class ProductServiceWrapper : IProductServiceWrapper
{
private readonly ProductService _service;
public int GetPrice() => _service.GetPrice();
}
以同样方式模拟 ProductServiceWrapper,如同对接口进行模拟一样。