I'm using Moq to drive my Model-View-Presenter unit tests. The particular view I'm testing is composed of a subview, which is modeled as an interface as illustrated here:
public interface ICustomerView:IView{
public int CustomerId {get;set;}
public IDateRangeView DateRangeView {get;set;}
}
In certain tests, I don't care to test the behavior or interaction with IDateRangeView; I simply want any invocations of that property not to throw null references exceptions, etc. It looks like Moq supports this feature by setting DefaultValue of a mock to DefaultValue.Mock, and then calling SetupAllProperties:
[Test]
public void some_test(){
var mockView = new Mock<ICustomerView>() { DefaultValue = DefaultValue.Mock };
mockView.SetupAllProperties();
}
However, the call to SetupAllProperties throws this exception:
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:
My work around is to set such interfaces manually, but there must be a less tedious solution:
[Test]
public void some_test(){
var mockView = new Mock<ICustomerView>();
var viewDateMock = new Mock<IDateRangeView>();
mockView.SetupGet(v=>v.DateRangeView).Returns(viewDateMock.Object);
}
Versions/Environment
Moq 3.1.416.3
.NET Framework 3.5 nUnit 2.5.0.9122 VS 2008 + Windows 7 x64
精彩评论