java - Can I inject primitive variable into mocked class using annotation? -


for example have handler:

@component public class myhandler {    @autowired   private mydependency mydependency;    @value("${some.count}")   private int somecount;    public int somemethod(){     if (somecount > 2) {     ...   } } 

to test wrote following test:

@runwith(mockitojunitrunner.class} class myhandlertest {    @injectmocks   myhandler myhandler;    @mock   mydependency mydependency;    @test   public void testsomemethod(){     reflectiontestutils.setfield(myhandler, "somecount", 4);     myhandler.somemethod();   } } 

i can mock variable somecount using reflectiontestutils. can somehow mock using mockito annotation?

there isn't built-in way this, , beware @injectmocks has downsides well: mockito's @injectmocks more of courtesy fully-safe feature, , fail silently if system under test adds fields.

instead, consider creating constructor or factory method testing: though test code should live in tests , not production classes, tests consumer of class, , can design constructor explicitly them.

@component public class myhandler {    @autowired   private mydependency mydependency;    @value("${some.count}")   private int somecount;    /** visible testing. */   myhandler(mydependency mydependency, int somecount) {     this.mydependency = mydependency;     this.somecount = somecount;   }    // .... } 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -