Working with Mockito

Mockito is an open source unit mocking framework for Java. It allows mock object creation, verification, and stubbing.

Mockito was moved to GitHub. You can visit https://github.com/mockito/mockito to get the source code, and visit http://code.google.com/p/mockito/ to learn more about Mockito.

Learning the significance of Mockito

We add automated unit tests to run and notify us in case any code breaks the system so that the wrong code can be identified and fixed very quickly.

But when an automated test suite takes time to execute, for instance, two hours to complete a build, it defeats the purpose of quick feedback. In Test-Driven Development (TDD), automated JUnit test cases are run to provide quick feedback. Here, a test should not take more than a few milliseconds to execute. When a test suite takes hours to execute, it blocks the progress of development.

A test suite takes time because individual tests take time to execute. The following are some reasons behind delays in test execution:

  • A test performs an integration task, such as acquiring a database connection, and then fetches data or updates data.
  • A test may connect to the Internet to download files or get the current stock price.
  • A test may send an invoice mail to a vendor. In order to send an e-mail, it has to interact with an SMTP server.
  • A test may print a bill, open a file, or perform an I/O operation.

Do we really need to perform all or any of these tasks to unit test our code?

If we don't perform these tasks, a few parts of the system remain untested. So querying the database or sending an e-mail is necessary to perform end-to-end system testing, but when a test interacts with an external resource, it is called an integration test. Due to external resource interaction, integration tests take time to execute but unit tests mock external dependencies using test doubles, and thus unit tests are executed very quickly.

Mockito provides APIs to mock external dependencies. It can mock a database connection with a mock implementation that doesn't interact with the real database, or it can mock an SMTP connection for an e-mail task. So Mockito provides APIs to isolate the actual logic from external dependencies to unit test it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.228