Suppose you had 2 classes, Listener and Talker. Talker has an event Talking, and when this event is fired, Listener should execute a void method HeardTalk, along these lines:
public class Talker
{
public event EventHandler Talking;
public void Talk()
{
if (Talking != null)
{
Talking(this, null);
}
}
}
public class Listener
{
public void StartListening(Talker talker)
{
talker.Talking += HeardTalk;
}
public void HeardTalk(object sender, EventArgs e)
{
// do something private here
}
}
How would you go about unit testing that once StartListening has been called, HeardTalk gets called, if there was no public state reflecting that the method was called? I could just add such a state for the purpose of validation, but it seems clumsy. Ideally, I would like to assert the call was made, in a manner similar to what Mocking frameworks do, but I can’t mock the class under test.
Is there an elegant way to assert that a method was called on the SUT, without modifying it just for the purpose of testability?
You can do such things easily with the commercial Typemock Isolator, which allows you to selectively ‘mock’ individual methods on ‘real’ objects.
The test would look like this:
Admittedly, Typemock Isolator comes with some license costs. But if you’re serious about testing and need to test a lot of stuff like the above, it’s worth every penny because of its strength and flexibility.
Notes:
HTH!
Thomas