C# – Problem mocking events attached to abstract class through constructor of other object

cmockingrhino-mocksunit testing

i have an abstract class and im trying to mock out events being attached to it using Rhino Mocks. Here a bit of the abstract class

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
}

ive marked the event as virtual so that it can be mocked.

In my app a Download is passed into the constructor of a DownloadEntity, within the constructore the download has its events hooked up, as follows

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

}

so, this is pretty straightforwards, i want to Mock out the Download and using a DownloadEntity Verify that the event is attached, for this i have used the fluent Rhino Mocks Syntax as follows

    [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();
    }

i get an expected = #1 actual #0 even though when i walk through the code i can see that the handler is attached to Mocked Download. This has got me really stuck and i cant help but think im missing something really obvious here.

Thanks!

Best Answer

I'm using Rhino Mocks 3.5 and this is all I have to do to test your functionality of the event binding properly.

[Test]
public void Download_attaches_events_when_created()
{
    // Arrange
    var download = MockRepository.GenerateMock<Download>();

    // Act
    var downloadEntity = new DownloadEntity(download);

    // Assert
    download.AssertWasCalled(x => x.DownloadProgress_Changed += Arg<EventHandler<DownloadProgressEventArgs>>.Is.Anything);
}

If you're not using 3.5 or higher, and you can upgrade, I'd consider it to make your tests simpler.

Related Topic