in JUnit, when should I use assertEquals() when should I use try...catch to verify results? -


e.g, in verifysthissetcorrectly() of following code, should use assertequals() check result or should throw exception caught try...catch of caller , let caller handle?

@parameters public static collection<object[]> methodparams() {     list<object[]> params = new arraylist<object[]>();     /* arg, errorstring */     params.add(new object[] {"arg1", null /*errorstring*/});     params.add(new object[] {"arg2", error_string1 /*errorstring*/}); } @test public void sampletest () {     try {         methodandwait(arg);         assertnull("expect error string" + errorstring, errorstring);     } catch (exception ex) {         assertnotnull("expect error string" + errorstring, errorstring);         asserttrue(ex.getmessage().contains(errorstring));     } }  private void methodandwait() {     call_remote_server_to_have_sth_set;     verifysthissetcorrectly(); }  private void verifysthissetcorrectly() {     int sth = getsth();     assertequals(sth == "5"); } 

in junit test, should use assertions assertequals() verify result of method call or state of object:

@test public void addingtwonumbersshouldwork() {   int result = calculator.add(5, 7);    assertequals(12, result);   assertfalse(calculator.hasoverflow()); } 

it's extremely rare use try , catch in junit test other testing code block throws expected exception:

@test public void setcolorshouldthrownullpointerexceptiononnullinput() {   try {     deathray.setcolor(null);     fail("expected nullpointerexception");   } catch (nullpointerexception expected) {     assertthat(expected.getmessage(), contains("death ray color"));   } } 

you not need use try , catch if method testing happens throw exception:

@test public void firedeathray() throws deathrayexception {   deathray.fire(); } 

in above test, if fire() throws deathrayexception (or runtime exception) firedeathray test fail.

in junit4, it's rarer use try , catch, because you can use expectedexception rule check if call throws expected exception.


Comments