我有一个抽象类,我试图用Rhino Mocks模拟出附加到它的事件。这里抽象类的一点嘲笑通过其他对象的构造函数附加到抽象类的事件
public abstract class Download
{
public virtual event EventHandler<DownloadProgressEventArgs> DownloadProgress_Changed;
protected virtual void OnDownloadProgressChanged(DownloadProgressEventargs e)
{
if(DownloadProgress_Changed != null)
{
DownloadProgress_Changed(this, e);
}
}
// abstract method declarations etc
}
我把事件标记为虚拟的,以便它可以被模拟。
在我的应用程序下载被送入DownloadEntity的构造函数中,constructore下载了它的事件挂接内,如下
public class DownloadEntity
{
private Download _download;
public DownloadEntity(Download download)
{
_download = download;
_download.DownloadProgressChanged += new EventHandler<DownloadProgressEventArgs>(download_DownloadProgressChanged);
}
public virtual void download_DownloadProgressChanged(object sender, DownloadProgressEventArgs e)
{
// stuff done here
}
// other code and stuff in the class
}
所以,这是非常straightforwards,我想模拟出的下载和使用DownloadEntity验证事件附加,为了这个,我已经使用了流畅的犀牛嘲笑语法如下
[Test]
public void DownloadAttachesEventsWhenCreated()
{
MockRepository mocks = new MockRepository();
Download dl = mocks.DynamicMock<Download>();
DownloadEntity dle;
With.Mocks(mocks).Expecting(delegate
{
dl.DownloadProgressChanged += new EventHandler<DownloadProgressEventArgs>(DummyHandler);
})
.Verify(delegate
{
// verify it is called by creating a new DownloadEntity and injecting the mock
dle = new DownloadEntity(dl);
});
}
void DummyHandler(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
即使当我浏览代码时,我也会看到该处理程序已附加到Mocked下载。这让我真的陷入了困境,我不能帮助,但我想在这里失去一些真正明显的东西。
谢谢!
我刚刚通过在以上测试中执行了以下操作 我将代码更改为 dl.DownloadProgressChanged + = null; LastCall.Constraints(Is.NotNull()); 为什么地球上它现在的工作? – Matt 2009-10-15 14:57:02