java - how to write a junit mokito test case -


how write junit mokito test case binding result @valid functionality if-else conditions example?

@requestmapping(value = "/scriptfile", method = requestmethod.post)      public string create(     @valid scriptfile scriptfile,      bindingresult result,      modelmap modelmap )  {              if (scriptfile == null)          throw new illegalargumentexception("a scriptfile required");       if (result.haserrors()) {                          modelmap.addattribute("scriptfile", scriptfile);                              modelmap.addattribute("showcases", showcase.findallshowcases());                              return "scriptfile/create";                      }                  scriptfile.persist();                  return "redirect:/scriptfile/" + scriptfile.getid();          }    

how write junit mokito test case above example?

it this. can use spy instead of mock if can instantiate object. or create modelmap instance , check if attributes set instead of mocking.

@mock private bindingresult result;  @mock private modelmap modelmap;  @mock  private scriptfile scriptfile;  @beforemethod public void setup() throws exception {     mockitoannotations.initmocks(this); }  @test(expectedexceptions = {illegalargumentexception.class})   public void shouldthrowillegalargumentexception() {     create(null, result, modelmap); }  @test public void shouldpersistfile() {     mockito.when(result.haserrors()).thenreturn(false);     mockito.when(scriptfile.getid()).thenreturn("file_id");      string output = create(scriptfile, result, modelmap);      mockito.verify(scriptfile, times(1)).persist();     assertequals("redirect:/scriptfile/file_id", output) }  @test public void shouldhandleerrors() {     mockito.when(result.haserrors()).thenreturn(true);     mockito.when(scriptfile.getid()).thenreturn("file_id");      string output = create(scriptfile, result, modelmap);      mockito.verify(modelmap, times(2)).addattribute(mockito.any(), mockito.any());     assertequals("scriptfile/create", output) } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -