I have a class which uses the DeviceWatcher class from Windows.Device.Enumeration:
Class A
{
var temp = DeviceInformation.CreateWatcher(x,y,z);
temp.Added += DoSomething;
public void DoSomething(DeviceWatcher sender, DeviceInformation args)
{
//Do something;
}
}
I want to unit test if Added event is called and DoSomething is invoked. My unit test looked like this:
class UnitTest{
var mockDeviceWatcher = new Mock<DeviceWatcher>;
this.A = this.container.Resolve<A>;
}
However, I could not resolve Mock<DeviceWatcher> since it is a sealed class. As a work around, I created a facade class B and an interfaceB which is mockable:
class B
{
private DeviceWatcher deviceWatcher;
public event TypedEventHandler<DeviceWatcher, DeviceInformation> Added
{
add { this.deviceWatcher.Added += value; }
remove { this.deviceWatcher.Added += value; }
}
}
I changed class A to use the facade class instead of the actual device watcher:
class A
{
A(B facadeB)
{
facadeB.Added += DoSomething;
}
public void DoSomething(DeviceWatcher sender, DeviceInformation args)
{
//Do something;
}
}
Now this helps me mock Device Watcher in the following way:
class UnitTest{
var mockDeviceWatcher = new Mock<IB>; //facade interface B
this.A = this.container.Resolve<A>;
mockDeviceWatcher.SetupAdd(m => m.Added += (sender, args) =>{});
mockDeviceWatcher.Raise(m =>m.Added += (sender, args) => {});
mockDeviceWatcher.Object.Added += (sender, args) =>{};
mockDeviceWatcher.VerifyAdd(m =>m.Added +(sender, args) =>{});
}
I get a test failure:
Expected invocation on the mock at least once but was never performed.
However, if I put breakpoints in DoSomething(), I can see them being hit, and if I replace the VerifyAdd with a VerifyAll, the test passes.
Question here:
- ) Am I doing the right thing by using facade/wrappers?
- ) Am I raising events in the right way to be tested?
- ) Why does
VerifyAllpass butVerifyAdddoes not?