【问题标题】:C# Unit Test NSubstitute Unable to Set Value in ObjectCacheC# 单元测试 NSubstitute 无法在 ObjectCache 中设置值
【发布时间】:2018-01-24 22:52:15
【问题描述】:

我无法在单元测试中使用 Set 在 ObjectCache 中插入缓存条目。

var objectCache = Substitute.For<ObjectCache>();
objectCache.Set("TestKey", object, Arg.Any<DateTimeOffset>());

当我进入我的代码时

var cachedData = _objectCache.Get("TestKey");
// cachedData is null

我正在使用 Nsubstitute 来模拟库。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 您在模拟对象上模拟 Set。模拟中实际上没有保存任何内容。您需要模拟该键的 Get 以获得所需的行为
  • 与问题没有具体关系,但是使用参数匹配器作为没有.Returns/.Received/.When的调用的参数,比如这个问题中使用的Set("TestKey", object, Arg.Any&lt;DateTimeOffset&gt;()),可能会导致问题测试。请参阅docs 了解更多信息。

标签: c# unit-testing nsubstitute objectcache


【解决方案1】:

您需要为Get 方法配置模拟。请参阅NSubstitute docsreturn 方法的示例。

类似...

var objectCache = Substitute.For<ObjectCache>();
objectCache.Get("TestKey").Returns(...what you want it to return);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2021-06-04
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多