我有一个单元测试来验证一个对象(比如说Foo)会Bar在某个eventArgs触发事件时调用某个方法(比方说).为了模拟所述方法,我使用虚拟和存根Foo类
Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);
mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result
Run Code Online (Sandbox Code Playgroud)
但是,上面的失败,Bar不会被调用,显然是因为Foo对象不是构造事件的.但是,如果我添加如下所示的行:
Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);
var workAround = stubbedFoo.Object //adding this workaround will work
mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result
Run Code Online (Sandbox Code Playgroud)
它会起作用,因为调用get on .Object显然会强制mock来构造对象.有没有比添加这条线更优雅的解决方案?
我认为你不能。我检查了最小起订量源并浏览了它,看起来在您调用之前,城堡的代理拦截器实际上并未创建.Object。看看这个痕迹:
public object Object
{
get { return this.GetObject(); }
}
private object GetObject()
{
var value = this.OnGetObject();
this.isInitialized = true;
return value;
}
Run Code Online (Sandbox Code Playgroud)
其次是
protected override object OnGetObject()
{
if (this.instance == null)
{
this.InitializeInstance();
}
return this.instance;
}
Run Code Online (Sandbox Code Playgroud)
这是做什么的:
private void InitializeInstance()
{
PexProtector.Invoke(() =>
{
this.instance = proxyFactory.CreateProxy<T>(
this.Interceptor,
this.ImplementedInterfaces.ToArray(),
this.constructorArguments);
});
}
Run Code Online (Sandbox Code Playgroud)
ProxyFactory 实际上创建对象并将其包装在代理中
public T CreateProxy<T>(ICallInterceptor interceptor, Type[] interfaces, object[] arguments)
{
var mockType = typeof(T);
if (mockType.IsInterface)
{
return (T)generator.CreateInterfaceProxyWithoutTarget(mockType, interfaces, new Interceptor(interceptor));
}
try
{
return (T)generator.CreateClassProxy(mockType, interfaces, new ProxyGenerationOptions(), arguments, new Interceptor(interceptor));
}
catch (TypeLoadException e)
{
throw new ArgumentException(Resources.InvalidMockClass, e);
}
catch (MissingMethodException e)
{
throw new ArgumentException(Resources.ConstructorNotFound, e);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1319 次 |
| 最近记录: |