c# - Testing Exceptions with Nunit -
iam using nunit unit tests , need unit test code throws exception.my code simillar this.
public class myclass { public int count { get; set; } public void foo() { seek { if (count >3) { throw new exception(); } } grab (exception e) { messagebox.show(e.message); } } } [testfixture] public class testmyclass { [test] public void testfoo() { var obj = new myclass(); obj.count = 4; assert.throws<exception>(obj.foo); } }
this give error this
expected: <system.exception> was: null
i found if remove seek grab block,unit test passes.but dont want alter actual code .please advise how can unit test abovementioned code , right way of doing it.
since method swallows exceptions, can't utilize assert.throws
since no exception thrown.
if want check exception handled in way create interface:
public interface iexceptionhandler { void handle(exception ex); } public void winformsexceptionhandler : iexceptionhandler { public void handle(exception ex) { messagebox.show(e.message); } } public class myclass { private readonly iexceptionhandler handler; public myclass(iexceptionhandler handler) { this.handler = handler; } public myclass() : this(new winformsexceptionhandler()) { } public int count { get; set; } public void foo() { seek { if (count >3) { throw new exception(); } } grab (exception e) { this.handler.handle(e); } } }
then can utilize mock in tests, illustration using rhinomocks do:
[test] public void testfoo() { var handler = mockrepository.generatemock<iexceptionhandler>(); var obj = new myclass(handler); obj.count = 4; obj.foo(); handler.assertwascalled(h => h.handle(arg<exception>.is.anything)); }
c# unit-testing exception nunit
No comments:
Post a Comment