【发布时间】: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