我想创建一个单元测试,方法如下所示
public async Task<Country> Get(string slug)
{
var entityId = GetCountryEntityId(string slug);
... Do stuff
}
调用这个私有方法
private string GetCountryEntityId(string slug)
{
var properties = new EntityProperties(slug, CacheHandlerKeys.Countries, "allCountries");
var entityId = _entityIdService.GetEntityId(properties);
if (string.IsNullOrEmpty(entityId))
{
var e = new NullEntityIdException(slug);
e.Data.Add("Slug", slug);
throw e;
}
return entityId;
}
它会检查缓存“allCountries”中是否存在与替换内存缓存中存在的“slug”匹配的项目
在调用我尝试测试的方法之前,我已在测试中添加了这些行。
var props = new EntityProperties(slug, CacheHandlerKeys.Countries, "allCountries");
_entityIdService.GetEntityId(props).Returns("Test");
其中 _entityIdService 是替代品。 接下来是方法的调用
var result = await repo.Get(slug);
我可以在调试时看到,当调用私有方法时,它正在访问我的替换版本的 IEntityIdService,使用与我的“props”变量的精确匹配,但它仍然返回一个空白字符串而不是文本“Test”。
如何让它返回文本“Test”?
成功。这是给我想要的代码。
_entityIdService.GetEntityId(Arg.Any<EntityProperties>()).ReturnsForAnyArgs(x => "Test");
var result = await repo.Get(slug);
当被测试方法调用时,这会返回文本“Test”。
关键在于传递给方法“GetEntityId”的参数,而不是传递显式的 EntityProperties 实现 - 我最初试图这样做,现在我给它内置的 Arg.Any 参数。
当你知道如何做时,显而易见。