java - Mock a method call from another class -


this question has answer here:

my code structure :

class {     void methoda() {         //some code         b b = new b();         response = b.methodb(arg1, arg2);         //some code using "response"     } } 

i unit testing class , don't want call methodb(). there way mock method call custom response. tried mockito mock method call below:

b classbmock = mockito.mock(b.class); mockito.when(classbmock.methodb(arg1, arg2)).thenreturn(customresponse); obja = new a(); obja.methoda(); 

on calling methoda() above way don't customresponse when methodb() called within a. when call methodb() classbmock, customresponse. there anyway can customresponse methodb() while calling methoda().

one common way of doing extracting creating of collaborator instance method, , spying class want test.

in case, rewrite a this:

public class {     public b createb() {         return new b();     }      public void methoda() {         //some code         b b = createb();         response = b.methodb(arg1, arg2);        //some code using "response"     } } 

now test can spy a instance you're testing, , inject mock b:

b classbmock = mockito.mock(b.class); mockito.when(classbmock.methodb(arg1, arg2)).thenreturn(customresponse); obja = mockito.spy(new a()); mockito.when(obja.createb()).thenreturn(classbmock()); obja.methoda(); 


edit:
if cannot modify a, way go use powermock. note code snippet shows relevant mocking, , doesn't display annotations required allow powermock instrument class:

b classbmock = mockito.mock(b.class); mockito.when(classbmock.methodb(arg1, arg2)).thenreturn(customresponse); powermockito.whennew(b.class).withnoarguments().thenreturn(classbmock); obja = new a(); obja.methoda(); 

Comments