我正在使用Moq来驱动我的Model-View-Presenter单元测试。我正在测试的特定视图由子视图组成,该视图被建模为如下所示的接口:
public interface ICustomerView:IView{
public int CustomerId {get;set;}
public IDateRangeView DateRangeView {get;set;}
}
在某些测试中,我不关心测试行为或与IDateRangeView的交互;我只是希望对该属性的任何调用都不要抛出空引用异常等。看起来Moq通过将mock的DefaultValue设置为DefaultValue.Mock,然后调用SetupAllProperties来支持此功能:
[Test]
public void some_test(){
var mockView = new Mock<ICustomerView>() { DefaultValue = DefaultValue.Mock };
mockView.SetupAllProperties();
}
但是,对SetupAllProperties的调用会抛出此异常:
System.ArgumentException occurred
Message="A matching constructor for the given arguments was not found on the mocked type."
Source="Moq"
StackTrace:
at Moq.Mock`1.<InitializeInstance>b__0()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.get_Object()
at Moq.Mock`1.GetObject()
at Moq.Mock.get_Object()
at Moq.MockDefaultValueProvider.ProvideDefault(MethodInfo member, Object[] arguments)
at Moq.Mock.<>c__DisplayClass27.<SetupAllProperties>b__23()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock.SetupAllProperties(Mock mock)
at Moq.Mock.<>c__DisplayClass27.<SetupAllProperties>b__23()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock.SetupAllProperties(Mock mock)
at Moq.Mock`1.SetupAllProperties()
InnerException: System.MissingMethodException
Message="Constructor on type 'DateRangeProxyf68a22c875334e7d858d8ccc5759ecaa' not found."
Source="mscorlib"
StackTrace:
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, IInterceptor[] interceptors)
at Moq.Mock`1.<InitializeInstance>b__0()
InnerException:
我的工作是手动设置这样的接口,但必须有一个不那么繁琐的解决方案:
[Test]
public void some_test(){
var mockView = new Mock<ICustomerView>();
var viewDateMock = new Mock<IDateRangeView>();
mockView.SetupGet(v=>v.DateRangeView).Returns(viewDateMock.Object);
}
版本/环境
Moq 3.1.416.3
.NET Framework 3.5
nUnit 2.5.0.9122
VS 2008 + Windows 7 x64