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);