Mocking
Last updated
Last updated
Understand what is a mock
Practice mocking on a code example
In groups of 3 answer to this question : in which cases do you use a Mock ?
Mock objects allow you to simulate the behavior of classes and interfaces
Letting the code in the test interact with them as if they were real
Mocks are used to test behavior of other objects, reals, but link to another object not available in test context or not implemented yet
Be able to execute tests in isolation
Replaces dependency from other object
Set expectations on calls to the dependent object
Set the exact return values it should give you to perform the test you want
When using mocks you need to always ask yourselves what are your test boundaries.
The system needs a DB access
The system call services that are not available
The system call APIs developed by other teams which are not implemented yet
We would like to test a system which convert an amount in a specific currency to another one. The converter method call a service to retrieve the change rate between the two currencies.
Some rules are checked during treatment :
In our Unit Tests methods the service is not accessible -> we need to “mock” it
Open the source code here
Demonstrate how to add Mockito to our tests
This annotation allows us to use the @Mock annotation (inject Mocks)
Learn more about it here
The production code is implemented as expected
Please add the tests to check it
When working with existing code and adding test on it : use your Code Coverage
Group sharing
Demo the solution in the dedicated branch
Think about what we did today.
If you had to explain the main idea of mocking to someone else, what would you say?
Write your explanation in a sentence or two on a post-it