[英]Moq - How to setup a Lazy interface
I want to mock a Lazy Interface and also Setup
a method to return false. 我想模拟一个惰性接口,还要
Setup
一个返回false的方法。
The problem is, when i run the test, I get a NotSupportedException: 问题是,当我运行测试时,出现NotSupportedException:
System.NotSupportedException: 'Invalid setup on a non-virtual (overridable in VB) member: mock => mock.Value
System.NotSupportedException:'在非虚拟(在VB中可重写)成员上的无效设置:模拟=>模拟值
Here is a simplified example: 这是一个简化的示例:
[TestMethod]
public void SomeTestMethod()
{
var someService = new Mock<Lazy<IService>>();
/*this line throws the exception*/
someService.Setup(x => x.Value.SomeMethod()).Returns(false);
...
}
Please consider that SomeMethod
is actually virtual, but somehow getting the lazy initialization using x.Value
is not supported by Moq. 请考虑
SomeMethod
实际上是虚拟的,但是Moq不支持使用x.Value
进行延迟初始化。
I didn't found a solution for this specific scenario but I did view some other approaches on declarations, but sadly didn't work for me. 我没有找到针对这种特定情况的解决方案,但我确实查看了声明的其他方法,但可惜对我没有用。
[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);
...
}
You started on the right track with 您从正确的轨道开始
var someService = new Mock<IService>();
var lazySomeService = new Lazy<IService>(() => someService.Object);
but the setup needs to be on the mock not the actual Lazy
implementation. 但是设置需要模拟而不是实际的
Lazy
实现。
someService.Setup(x => x.SomeMethod()).Returns(false);
That way when the Lazy.Value
is called, it will be using the mock. 这样,当调用
Lazy.Value
时,它将使用模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.