Mockito Overview - Mockito

What is Mocking?

Mocking is a process to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a functionality. Mock objects performs the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it.

What is Mockito?

Mockito facilitates creating mock objects seamlessly. Mockito uses Java Reflection to produce the mock objects for a given interface. Mock objects are known as proxy for actual implementations.

Let’s consider a case of Stock Service which returns the price details of a stock. While development, the actual stock service cannot be used to get real-time data. So we use dummy implementation of the stock service.

What are the benefits of Mockito?

  • No Handwriting − No need to write mock objects on your own.
  • Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime.
  • Return value support − Supports return values.
  • Exception support − Supports exceptions.
  • Order check support − Supports check on order of method calls.
  • Annotation support − Supports creating mocks using annotation.

Consider the following code snippet.

Here we are discussing about the important concepts of the above program. Find the complete code in the chapter First Application.

  • Portfolio − An object to carry a list of stocks and to get the market value computed using stock prices and stock quantity.
  • Stock − An object to carry the details of a stock such as its id, name, quantity, etc.
  • StockService − A stock service returns the current price of a stock.
  • mock(...) − Mockito created a mock of stock service.
  • when(...).thenReturn(...) − Mock implementation of getPrice method of stockService interface. For googleStock, return 50.00 as price.
  • portfolio.setStocks(...) − The portfolio now contains a list of two stocks.
  • portfolio.setStockService(...) − Assigns the stockService Mock object to the portfolio.
  • portfolio.getMarketValue() − The portfolio returns the market value based on its stocks using the mock stock service.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Mockito Topics