mocking - How to mock local variables in java? -


this question has answer here:

in situation?

class {   public void f() {     b b = new b();     c c = new c();     // use b , c, , how modify behaviour?   } } 

how can fullfill idea powermock , easymock?

i don't want change compact code test reasons.

you can this, see answer matt lachman. approach isn't recommended however. it's bit hacky.

the best approach delegate creation of dependant objects factory pattern , inject factories a class:

class bfactory {      public b newinstance() {         return new b();     } }  class cfactory {      public c newinstance() {         return new c();     } }  class {      private final bfactory bfactory;     private final cfactory cfactory;      public a(final bfactory bfactory, final cfactory cfactory) {         this.bfactory = bfactory;         this.cfactory = cfactory;     }      public void f() {         b b = bfactory.newinstance();         c c = cfactory.newinstance();     } } 

you mock factories return mock instances of dependent classes.

if reason not viable can create factory methods in a class

class {      public void f() {         b b = newb();         c c = newc();     }      protected b newb() {         return new b();     }      protected c newc() {         return newc();     } } 

then can use spy mocks factory methods.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -