Question

New to mockito. I am still trying to understand how this works.

For instance, if I mock a class, does it automatically mock all the classes inside that class?

  class Bank {
     Customer cust;
     cust.deposit(102, CHECK);
  }

  class Customer {
     Account acct;
     public deposit(int amount, Type t) {
         return account.getLimits( t );
     }
  }

  class Account {
    AccTypes types;
    public getLimits(Type t)  {
      int res =  types.getAccountType(t);
      return res;
    }
  }

  class AccTypes {
    pulic getACcountTypes( Type t){
       return something;
    }
  }
  1. If I mock Bank, does it automatically mock Account,Customer and AccTypes as well?
  2. How do I test the deposit() method? (It has to eventually reach getAccountTypes in AccTypes) (code please, with explanation).

Note that its a very simple (actually pseudo code). So may not be a perfect java code. But this is just to give you an idea what I am trying to achieve.

Was it helpful?

Solution

A mock will only implement the same non-private methods as the class or interface you mock. It won't contain any references to any others of your objects, even if the class you mock has references.

To unit test the behavior of the deposit() method you would create a mock for all dependencies of Customer. The only dependency is Account so let's mock it:

 Account accMock = Mockito.mock(Account.class);
 Mockito.when(accMock.getLimits(Type.SOME_TYPE)).thenReturn(500);

Now whenever anything calls accMock.getLimits() with Type.SOME_TYPE, it will return 500. If it is called with any other parameter, a default value is returned (0, false null, depending on the return type). Next we create the object to be tested and set the account field to our mock:

 Customer customer = new Customer();
 customer.setAccount(accMock);

Call the method to be tested, i.e. deposit():

 customer.deposit(100, Type.SOME_TYPE);

Now verify the behavior of the method. We expect that it calls getLimits() with Type.SOME_TYPE and nothing else:

 // verify that getLimits() is invoked for Type.SOME_TYPE
 Mocktio.verify(accMock).getLimits(Type.SOME_TYPE);
 // verify that no other method is called on accMock
 Mockito.verifyNoMoreInteractions(accMock);

OTHER TIPS

I may be misunderstanding your question, but when you mock Bank with Mockito and call said mock, you are no longer calling the implementing logic in the Bank class, and so there is no reason Mockito would mock out those dependant classes.

If you wish to return a mocked class from an invocation to Bank, then you can setup your Bank mock to return what you want for the specified invocation, otherwise there is no need to create mocks for those other classes.

E.g.

@Mock
private Bank bankMock;

when(bankMock.getAccount().thenReturn(mock(Account.class));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top