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.
- [SetUp]
- publicvoid Setup()
- {
- webClient = Mock.Create<WebClient>();
- }
Next the mocking here takes place in two part. First, DownloadDataCompletedEventArgs is mocked to return an expected data when Result property is get.
- var e = Mock.Create<DownloadDataCompletedEventArgs>();
- var data = newbyte[] { 1, 2, 3 };
- Mock.Arrange(() => e.Result).Returns(data);
This is followed by an arrange that will raise the expected event when DownloadDataAsync is invoked.
- Mock.Arrange(() => webClient.DownloadDataAsync(Arg.IsAny<Uri>()))
- .Raises(() => webClient.DownloadDataCompleted += null, null, e);
Finally, the whole test method ends up like:
- [Test]
- publicvoid ShouldAssertExepectedDataWhenDownloadIsCompleted()
- {
- var count = 0;
- var e = Mock.Create<DownloadDataCompletedEventArgs>();
- var data = newbyte[] { 1, 2, 3 };
- Mock.Arrange(() => e.Result).Returns(data);
- Mock.Arrange(() => webClient.DownloadDataAsync(Arg.IsAny<Uri>()))
- .Raises(() => webClient.DownloadDataCompleted += null, null, e);
- byte[] exepectedData = null;
- webClient.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs de)
- {
- exepectedData = de.Result;
- count++;
- };
- webClient.DownloadDataAsync(newUri("http://example.de"));
- Assert.That(count, Is.EqualTo(1));
- Assert.That(exepectedData.Length, Is.EqualTo(data.Length));
- }
The above example is done using JustMock SP1. You can further download the code here:
Happy coding !!