java - How to write a Junit test case for a method in springboot without hardcoding -


new junit test case , want know test case code here without hardcoding values.

my code

public jsonobject getlistofallforms() {      list<forms> forms = formname.getinstance().getformlist();     int totalnumberofforms = 0;     list<string> formids = new arraylist<string>();     try {         (int = 0; < forms.size(); i++) {             form formob = forms.get(i);             formids.add(formob.getformid());             totalnumberofforms = forms.size();          }      } catch (exception e) {         e.printstacktrace();     }     jsonobject formslistobject = new jsonobject();     formslistobject.put("formids", formids);     formslistobject.put("totalnumberofforms", totalnumberofforms);     return formslistobject; } 

my controller code is:

@requestmapping(value = "/new/getforms/{formid}", method = requestmethod.get) public jsonobject getformbyformid(@pathvariable("formid") string formid) {     return newformname.getformbyformid(formid); } 

if want test getlistofallforms problem line...

list<forms> forms = formname.getinstance().getformlist(); 

this line couples formname hard method. bad.

a better way provide formname instance when instantiating class, example, let's assume name of class myclass..

private formname formname;  public myclass(formname formname) {      this.formname = formname; } 

this can used via spring or manually. via spring formname instance needs bean, can add @autowired constructor if myclass bean.

what advantage now? easy, test case, can simple thing...

public void somegreattestname() {     formname formname = ...; // either create new, fake 1 or mock 1 (see below)     jsonobject object = new myclass(formname).getlistofallforms();      // test object correct } 

doing means can inject fake or mock formname there, return data want test , remove need have actual "live" formname there. in other words, can fake/mock dependency formname. way, test uses test data , don't have hardcode live values there.

mocking can done via mockito, example, suggest giving try, in case, creating new "fake" formname may suffice.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -