Creating mocks in code

Before a mock is interacted with, it needs to be created. Mockito gives you several overloaded versions of the Mockito.mock method. Let's take a look at a few of them:

  • mock(Class<T> classToMock): This method creates a mock of a given class with a default answer set to returning default values (if not overriden by a custom Mockito configuration). When creating mocks in code, you will most likely be using this method.
  • mock(Class<T> classToMock, String name): This method creates a mock of a given class with a default answer set to returning default values. It also sets a name to the mock. This name is present in all verification messages. That's very useful in debugging, since it allows you to distinguish the mocks.
  • mock(Class<T> ...

Get Mockito Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.