How to raise event for a mocked call.

Recently, while i was working with a support issue , i found this interesting piece of test code that i would like to share here. This is actually written by Stefan Lieser (clean code developer from Germany forwarded to me by Jan from Telerik Germany). As the title states,  it is to mock a specific event for an expected call.

 

Now Stefan wants to raise an event from WebClient class of System.Net for a download operation. Therefore, first the WebClient class is mocked during setup.

  1. [SetUp]
  2. public void Setup()
  3. {
  4.     webClient = Mock.Create<WebClient>();
  5. }

Next the mocking here takes place in two part. First, DownloadDataCompletedEventArgs is mocked to return an expected data when Result property is get.

  1.  var e = Mock.Create<DownloadDataCompletedEventArgs>();
  2.  
  3.  var data = new byte[] { 1, 2, 3 };
  4.  
  5.  Mock.Arrange(() => e.Result).Returns(data);

 

This is followed by an arrange that will raise the expected event when DownloadDataAsync is invoked.

  1. Mock.Arrange(() => webClient.DownloadDataAsync(Arg.IsAny<Uri>()))
  2.     .Raises(() => webClient.DownloadDataCompleted += null, null, e);

 

Finally, the whole test method ends up like:

  1.   [Test]
  2.   public void ShouldAssertExepectedDataWhenDownloadIsCompleted()
  3.   {
  4.       var count = 0;
  5.  
  6.       var e = Mock.Create<DownloadDataCompletedEventArgs>();
  7.       
  8.       var data = new byte[] { 1, 2, 3 };
  9.      
  10.       Mock.Arrange(() => e.Result).Returns(data);
  11.      
  12.       Mock.Arrange(() => webClient.DownloadDataAsync(Arg.IsAny<Uri>()))
  13.           .Raises(() => webClient.DownloadDataCompleted += null, null, e);
  14.  
  15.       byte[] exepectedData = null;
  16.  
  17.       webClient.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs de)  
  18.       {
  19.           exepectedData = de.Result;
  20.           count++;
  21.       };
  22.  
  23.       webClient.DownloadDataAsync(new Uri("http://example.de"));
  24.  
  25.  
  26.       Assert.That(count, Is.EqualTo(1));
  27.       Assert.That(exepectedData.Length, Is.EqualTo(data.Length));
  28.   }

 

The above example is done using JustMock SP1. You can further download the code here:

 

Happy coding !!