NSubstitute模拟依赖后,如何让被测方法调用的私有方法返回指定值?
问题原因与解决方案
问题根源在于NSubstitute默认按引用匹配参数:你测试代码中创建的props实例,和私有方法里new EntityProperties(...)生成的是两个不同的对象,因此之前设置的_entityIdService.GetEntityId(props).Returns("Test")不会触发,NSubstitute会返回默认的null。
以下是几种可行的解决方法:
方法1:让EntityProperties实现值相等(推荐,若可修改类)
如果EntityProperties是你可控的类,重写Equals和GetHashCode方法,让NSubstitute能通过属性值判断两个实例是否相等:
public class EntityProperties { public string Slug { get; } public string CacheKey { get; } public string AllCountriesKey { get; } public EntityProperties(string slug, string cacheKey, string allCountriesKey) { Slug = slug; CacheKey = cacheKey; AllCountriesKey = allCountriesKey; } public override bool Equals(object obj) { return obj is EntityProperties props && Slug == props.Slug && CacheKey == props.CacheKey && AllCountriesKey == props.AllCountriesKey; } public override int GetHashCode() { return HashCode.Combine(Slug, CacheKey, AllCountriesKey); } }
修改后,你原来的测试代码就能正常触发返回"Test"的逻辑。
方法2:使用NSubstitute参数匹配器(无需修改类)
如果无法修改EntityProperties类,用参数匹配器通过Lambda表达式检查参数属性值,替代引用匹配:
_entityIdService.GetEntityId(Arg.Is<EntityProperties>(p => p.Slug == slug && p.CacheKey == CacheHandlerKeys.Countries && p.AllCountriesKey == "allCountries" )).Returns("Test");
只要私有方法传入的EntityProperties实例满足上述属性条件,就会返回"Test"。
方法3:宽松匹配(适合无需严格参数校验的场景)
如果不需要精确匹配参数,可直接匹配任意EntityProperties实例:
_entityIdService.GetEntityId(Arg.Any<EntityProperties>()).Returns("Test");
内容的提问来源于stack exchange,提问作者Username_null
相关产品推荐
相关产品推荐

