c# - Unit Testing - Raising static event to test proper event handler assignment -
i have class static event.
public class eventorigin { public static event handler eventoccurred; public delegate void handler(string arg1, string arg2); } i have different class hooks these events. test these events hooked into.
public static class consumesevent { public static register(){ eventorigin.eventoccurred += eventorigin_eventoccurredhandler; } public static void eventorigin_eventoccurredhandler(string arg1, string arg2){ //some stuff happens here } } what need test when eventorigin.eventoccurred fired after consumesevent.register() appropriate handler being fired. seems mean must raise eventorigin.eventoccurred event in test.
i'm guessing perhaps reflection used. there particular pattern may make easier , obviate need reflection in unit tests?
i got around deciding don't need raise event myself. instead can have private method raise event , use privatetype invoke method.
public class eventorigin { public static event handler eventoccurred; public delegate void handler(string arg1, string arg2); #region testability seams private static raiseeventoccurred(string arg1, string arg2) { if(eventoccurred != null) eventoccurred(arg1, arg2); } #endregion } which later consumed in test so:
private void wheneventraised_somestuffhappens(){ privatetype eventorigintype = new privatetype(typeof(eventorigin)); eventorigintype.invokestatic("raiseeventoccurred", "arg1", "arg2"); assert.istrue(overthinkingtheproblemisdangerous); } a nice side effect code around raising event gets null checks out of immediate area actual work happening, removing bit of noise areas raise these methods .
Comments
Post a Comment