2

So I'm trying to mock a method call inside another method, here's the pseudo code

class A{ public String getAName(String id){ B b = new B(); // do something return b.getBName(id); } } testgetName{ public void testA(){ B mockB = mock(B.class); Mockito.doReturn("Bar").when(mockB).getBName(id); A a = new A(); a.getAName(id); //this still calls "b.getBName(id)" in class implementation } } 

The problem here is a.getAName still calls b.getBName(id) - not sure why?

Any suggestions on how should I mock b.getBName(id) properly

Thanks

2
  • 2
    You cannot mock objects that are created by your object under test with new, since you have no control over those objects. You would have to make the B a field of class A and then inject it during your test. This is one of the reasons why people like dependency injection :) Commented Feb 16, 2018 at 21:25
  • One suggestion, you have a comment in your code that reads // do something. I will if this is a method call that takes B, to mock this method, or even better, use an ArugmentCaptor to capture the B passed to the method. This all hinges on what // do something actually does Commented Feb 16, 2018 at 21:30

1 Answer 1

7

Because you are not injecting/using the mock object inside class A. In class A you are creating a new B object. So, mock object is never used. To fix this change your Class A implementation to below:

B as member of class:

class A{ B b; public String getAName(String id){ // do something return b.getBName(id); } } 

then in your test method inject the mock object to the B member inside class A. See below:

public void testA()(){ B mockB = mock(B.class); Mockito.doReturn("Bar").when(mockB).getBName(id); A a = new A(); a.b = mockB; //add this line to use mock in A String testStr = a.getAName(id); //this still calls "b.getBName(id)" in class implementation System.out.println(testStr); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.