【问题标题】:Moq - How to setup a Lazy interfaceMoq - 如何设置惰性界面
【发布时间】:2019-02-06 01:27:38
【问题描述】:

我想模拟一个 Lazy Interface 以及 Setup 一个返回 false 的方法。

问题是,当我运行测试时,我得到了 NotSupportedException:

System.NotSupportedException: '非虚拟(在 VB 中可覆盖)成员上的设置无效:mock => mock.Value

这是一个简化的例子:

[TestMethod]
public void SomeTestMethod()
{
    var someService = new Mock<Lazy<IService>>();

    /*this line throws the exception*/  
    someService.Setup(x => x.Value.SomeMethod()).Returns(false);
    ...
}

请考虑 SomeMethod 实际上是虚拟的,但 Moq 不支持以某种方式使用 x.Value 进行延迟初始化。

我没有找到针对这种特定情况的解决方案,但我确实查看了其他一些关于声明的方法,但遗憾的是对我不起作用。

[TestMethod]
public void SomeTestMethod()
{
    var someService = new Mock<IService>();
    var lazySomeService = new Lazy<IService>(() => someService.Object);

    //tried this but won't compile
    //lazySomeService.Setup(x => x.Value.SomeMethod()).Returns(false);
    //lazySomeService.Value.Setup(x => x.SomeMethod()).Returns(false);
    ...
}

【问题讨论】:

    标签: c# unit-testing mocking moq


    【解决方案1】:

    你从正确的轨道开始

    var someService = new Mock<IService>();
    var lazySomeService = new Lazy<IService>(() => someService.Object);
    

    但设置需要模拟而不是实际的Lazy 实现。

    someService.Setup(x => x.SomeMethod()).Returns(false);
    

    这样当Lazy.Value 被调用时,它将使用模拟。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      相关资源
      最近更新 更多