Reputation: 3854
I have been using a pattern for some time. And I wonder if I am doing the right thing. I have a controller class that listens for events, and executes a private method when the event is raised. It goes a little something like this:
public class MyController
{
public MyController(IMyEventRaiser eventRaisingObject)
{
eventRaisingObject.MyEvent += HandleEvent;
}
private void HandleEvent(object sender, EventArgs args)
{
// SOME STUFF I WANT TO TEST!!
}
}
public class EventRaisingClass : IMyEventRaiser
{
public event EventHandler<EventArgs> MyEvent;
}
The only way to test the code in MyController.HandleEvent is to create a stub:IMyEventRaiser that raises the code.
I am not sure if this design is proper. On the one hand, I want to keep the HandleEvent method private, in order to illustrate that only an event can trigger it. On the other hand, it the private method contains key business logic, so I feel like it should be public or at least internal, which will also make it a lot easier to unit-test.
What do You lot think?
Regards, Morten
Upvotes: 3
Views: 3426
Reputation: 40336
What you've got sounds like a (mild) violation of SRP. Your controller both responds to events and holds the complicated logic that is executed for a particular event. What if your controller were simply to dispatch the necessary data to a dedicated Processor that did the real work? That Processor's method would necessarily be public - and therefore testable! Isn't it nice how TDD points out SRP violations?
Upvotes: 6
Reputation: 4459
Have you looked into Mocking Frameworks? "Moq" supports raising an event from a mocked type:
Mock<IMyEventRaiser> mock = new Mock<IMyEventRaiser>()
mock.Raise(e => e.MyEvent, EventArgs.Empty);
Upvotes: 2