c# - Negative tests - should I expect the exact exception? -
consider following method
public void foo(string str) { if (str == null) throw new argumentnullexception("str"); if (str.length != 5) throw new myexception(); }
suppose want write negative test so:
public void testfoo() { try { foo(null); //this remote call (e.g. wcf) assert.fail("expected argumentnullexception"); } catch (argumentnullexception) {} //should "exception" instead? try { foo("four"); //this remote call (e.g. wcf) assert.fail("expected myexception"); } catch (myexception) {} //should "exception" instead? }
it seems me catching specific exception above implementation detail, may make test brittle , coupled implementation (rather interface). myexception
change 1 day, argumentnullexception
may be, say, wrapped inside other exception (for example future wcf behavior). typically test knows "four" should fail, , that's cares - failure.
the exception (no pun intended) perhaps cases exception translated passed on user, such user-friendly messages (e.g. usernametakenexception
mapped user name taken, try different one). in such cases you'd want make sure correct error conveyed. it's little problematic since mean different type of exception each possible user error, may not bad (usually there aren't many of those).
does line of thinking make sense ? should indeed catch generic exception
in test cases don't involve user-facing exceptions ?
simply write @ least 4 tests:
[test] [expectedexception(typeof(argumentnullexception))] public void testfoofornull() { foo(null); } [test] [expectedexception(typeof(myexception))] public void testfooforinvalidsizetooshort() { foo("1234"); } [test] [expectedexception(typeof(myexception))] public void testfooforinvalidsizetoolong() { foo("123456"); } [test] public void testfoo() { foo("12345"); }
when writing unit tests, it's best treat 1 particular case per test.
Comments
Post a Comment