mockito - Is there any way to mock field of Class -


here's case, have class has 1 member field b. , want test , in unit test, mocked , need call method f() invoke b's f(). b variable in mocked null, throw npe, , have no get/set method b, there way mock b ? thanks

public static class b{     public void f() {      }   }    public static class {     b b;      public void f() {       b.f();     }   } 

if want mock out b property of in test, you've given b property default (package-private) access, long test in same package replace b property directly.

@test public void testb() {     undertest = new a();     b mockedb = mockito.mock(b.class);     undertest.b = mockedb;      undertest.f();      mockito.verify(mockedb).f(); } 

as aside, dislike using package-private access mess around member properties tests, , instead recommend dependency injection framework guice or spring di constructor injection.

however you've described you've mocked out a, i'd have thought if case f() method of nothing - wouldn't null pointer exception call mock replace real b property , void method nothing. please can provide more details if case?


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -