java - How should I approach or shouldn't unit test? -


i have huge codebase written else not unit tested @ all. want add unit testing spring application.but code of decoupled , times code not testable. how should approach should start low level objects or high level once , can give me step step example of how write unit tests spring application.

you can transform @autowired attributes @autowired constructors. check example:

@component public class someclass {     @autowired     private somedependency somedependency;      public ... dosomething(...) {         ...     } } 

can transformed to

@component public class someclass {      private somedependency somedependency;      @autowired     public someclass(somedependency somedependency) {         this.somedependency = somedependency;     }      public ... dosomething(...) {         ...     } } 

in fact, injection method preferred since object has all dependencies needs when constructor finishes. in first approach need like:

someclass someclass = new someclass(); someclass.setsomedependency(somedependency); // <- need add 

also happen!

someclass someclass = new someclass(); someclass.methodthatusessomedependency(); // <- nullpointerexception since somedependency not initialized! 

so, using constructor injection safe! add bit of safety setting dependencies final must initialized when constructor ends:

@component public class someclass {      private final somedependency somedependency;      @autowired     public someclass(somedependency somedependency) {         // removing line cause compile time error         this.somedependency = somedependency;     }      public ... dosomething(...) {         ...     } } 

so, summing up: move @autowired annotation constructor , go fine.

once have constructor dependencies arguments unit testing should trivial


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -