Nsubstitute 如何模拟被测试方法调用的私有方法

Nsubstitute How to mock private method called by method being tested

提问人:Username_null 提问时间:11/17/2023 最后编辑:Username_null 更新时间:11/17/2023 访问量:12

问:

我想创建一个单元测试,这种方法看起来像这样

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”?

单元测试 模拟 nsubstitute

评论


答:

0赞 Username_null 11/17/2023 #1

成功。这是为我提供我想要的东西的代码。

_entityIdService.GetEntityId(Arg.Any<EntityProperties>()).ReturnsForAnyArgs(x => "Test");

var result = await repo.Get(slug);

当被测试的方法调用时,这将返回文本“Test”。

关键在于传递给方法“GetEntityId”的参数,而不是传递显式的 EntityProperties 实现 - 我最初试图这样做,现在我给它内置的 Arg.Any 参数。

当您知道如何操作时,这是显而易见的。