Testable code: Attach event handler in constructor

Viewed 1356

as for my understanding, part of writing (unit-)testable code, a constructor should not do real work in constructor and only assigning fields. This worked pretty well so far. But I came across with a problem and I'm not sure what is the best way to solve it. See the code sample below.

class SomeClass
{
    private IClassWithEvent classWithEvent;

    public SomeClass(IClassWithEvent classWithEvent)
    {
        this.classWithEvent = classWithEvent;

        // (1) attach event handler in ctor.
        this.classWithEvent.Event += OnEvent;
    }

    public void ActivateEventHandling()
    {
        // (2) attach event handler in method
        this.classWithEvent.Event += OnEvent;
    }

    private void OnEvent(object sender, EventArgs args)
    {
    }
}

For me option (1) sounds fine, but it the constructor should only assign fields. Option (2) feels a bit "too much".

Any help is appreciated.

4 Answers
Related