If you have a class that contains an event, you'll want to write a unit test to test that the event gets fired at the right time and under the right conditions. The problem is that you would typically hook up an event handler in your unit test class that can run an assert to check if the event gets fired:
private bool _fired; [Test] public void CheckVisiblityEvent() { _fired = false; ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build(); vm.VisibilityChanged += new ImageGroupListItemViewModel.ImageGroupVisibilityChangedEventHandler(vm_VisibilityChanged); vm.Visible = true; Assert.IsTrue(_fired); } void vm_VisibilityChanged(object sender, ImageGroupVisibilityEventArgs args) { _fired = true; }
This is a bit sloppy. Instead, we could improve on this by using and anonymous method:
[Test] public void CheckVisiblityEvent() { bool fired = false; ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build(); vm.VisibilityChanged += delegate(object sender, ImageGroupVisibilityEventArgs e) { fired = true; }; vm.IsVisible = true; Assert.IsTrue(fired); }
More compact and easier to follow. Plus, the test code is all in one place. We can improve this even more with a lambda expression:
[Test] public void CheckVisiblityEvent() { bool fired = false; ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build(); vm.VisibilityChanged += (s, e) => fired = true; vm.IsVisible = true; Assert.IsTrue(fired); }
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.