c# - unit testing a class with event and delegate -
i new testing please help.
i have following class
public delegate void oninvalidentrymethod(itnentry entry, string message); public class entryvalidator { public event oninvalidentrymethod oninvalidentry; public bool isvalidentry(itnentry entry, string ticker) { if (!isfieldvalid(entry, ticker.trim().length.tostring(), "0")) return false; return true; } private bool isfieldvalid(itnentry entry, string actual, string invalidvalue) { if (actual == invalidvalue) { raiseinvalidentryevent(entry); return false; } return true; } private void raiseinvalidentryevent(itnentry entry) { if (oninvalidentry != null) oninvalidentry(entry, "invalid entry in list: " + entry.list.name + "."); } }
i have written test case far struggling event , delegate shown below
[testfixture] public class entryvalidatortests { private entryvalidator _entryvalidator; private faketnentry _selectedentry; private string _ticker; [setup] public void setup() { _entryvalidator = new entryvalidator(); _ticker = "bol"; } private faketnentry makeentry(string ticker) { return new faketnentry { ticker = ticker}; } [test] public void isvalidentry_withvalidvalues() { _selectedentry = makeentry(_ticker); assert.istrue(_entryvalidator.isvalidentry(_selectedentry, _selectedentry.ticker)); } [test] public void isvalidentry_withinvalidticker() { _selectedentry = makeentry(""); assert.isfalse(_entryvalidator.isvalidentry(_selectedentry, _selectedentry.ticker)); } }}
please can help? thanks..
it's simplest subscribe event using anonymous method:
[test] public void isvalidentry_withvalidvalues() { _selectedentry = makeentry(_ticker); _entryvalidator.oninvalidentry += delegate { assert.fail("shouldn't called"); }; assert.istrue(_entryvalidator.isvalidentry(_selectedentry, _selectedentry.ticker)); } [test] public void isvalidentry_withinvalidticker() { bool eventraised = false; _selectedentry = makeentry(""); _entryvalidator.oninvalidentry += delegate { eventraised = true; }; assert.isfalse(_entryvalidator.isvalidentry(_selectedentry, _selectedentry.ticker)); assert.istrue(eventraised); }
in second test might want validate event arguments expected too.
also note "invalid" 1 word - test should isvalidentry_withinvalidticker
. i'd not bother setup - i'd declare new local variables in each test.
Comments
Post a Comment