我有这个界面:
public interface IViewModelCache
{
IViewModel GetViewModel(Type viewModelType);
}
我用这段代码嘲笑它:
var cacheMock = Mock.Of<IViewModelCache>();
Mock.Get(cacheMock)
.Setup(cache => cacheMock.GetViewModel(typeof(IViewModel)))
.Returns(Mock.Of<IViewModel>());
但它会抛出
&#34;不支持指定的方法。&#34;,
有什么不对?
堆栈跟踪是:
在Moq.Mock.FluentMockVisitor.VisitMember(MemberExpression节点)
在Moq.Mock.FluentMockVisitor.Accept()at Moq.Mock.FluentMockVisitor.Accept(表达式表达式,模拟模拟)
在Moq.Mock.GetInterceptor(Expression fluentExpression,Mock mock)
在Moq.Mock。&lt;&gt; c__DisplayClass65_02.<Setup>b__0() at Moq.PexProtector.Invoke[T](Func
1函数)at Moq.Mock.Setup [T,TResult](模拟1 mock, Expression
1表达式, 条件条件)在Moq.Mock1.Setup[TResult](Expression
1 表达)
我也试过了:
Mock.Get(cacheMock)
.Setup(cache => cacheMock.GetViewModel(It.IsAny<Type>()))
.Returns(Mock.Of<IViewModel>());
那一个:
Mock.Get(cacheMock)
.Setup(cache => cacheMock.GetViewModel(It.IsAny<Type>()))
.Returns(new Mock<IViewModel>().Object);
两者都抛出相同的异常。
答案 0 :(得分:2)
安装程序中的表达式错误。尝试使代码更清晰,以便理解意图。
var cache = Mock.Of<IViewModelCache>();
var viewModel = Mock.Of<IViewModel>();
var viewModelType = typeof(IViewModel);
Mock.Get(cache)
.Setup(mock => mock.GetViewModel(viewModelType))
.Returns(viewModel);
答案 1 :(得分:1)
你应该返回mock的对象而不是mock本身。
Returns(Mock.Of<IViewModel>())
应该是
Returns(new Mock<IViewModel>().Object)
<强>更新强>
试试这个
var cacheMock = new Mock<IViewModelCache>();
cacheMock.Setup(c => c.GetViewModel(typeof(IViewModel)))
.Returns(new Mock<IViewModel>().Object);
答案 2 :(得分:0)
你有一个错字:
Mock.Get(cacheMock)
.Setup(cache => cacheMock.GetViewModel(typeof(IViewModel)))
.Returns(Mock.Of<IViewModel>());
应该是(注意Setup
电话):
Mock.Get(cacheMock)
.Setup(cache => cache.GetViewModel(typeof(IViewModel)))
.Returns(Mock.Of<IViewModel>());
答案 3 :(得分:0)
最后有效:
public static IViewModelCache MockViewModelCache()
{
var cache = Mock.Of<IViewModelCache>();
var viewModel = Mock.Of<RoutableViewModelBase<IReportData>>();
Mock.Get(cache)
.Setup(mock => mock.GetViewModel(It.IsAny<Type>)))
.Returns(viewModel);
return cache;
}