1

Im trying to understand how all things are related with Spring. However I do not understand why mockito is used when unit testing spring code? Can not spring handle to same DI that mockito does? What is it that mockito contributes that is not possible to do with pure spring?

Clarification: My thinking goes that I can just use a different application context for testing where I create the stub beans I need as dummy objects.

user3139545
  • 6,882
  • 13
  • 44
  • 87

2 Answers2

6

Spring is not a mocking framework. It's a dependency injection framework.

You use Mockito because it allows mocking collaborators of the class under test. So, if you're testing a service, and this service uses a repository that gets and stores data in a database, you mock the repository so that your test is a real, isolated unit test that doesn't need an Oracle database to run.

Read https://stackoverflow.com/a/28783849/571407 for a more detailed introduction to mocking.

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

You don't need Mockito to test Spring applications. You can start your server and use the injected dependency directly. But sometimes it is easier to mock one (or more) dependency(ies), for example a select of your database, because you want to test the code that you have written and not the select of the database, which also includes that you need a database with some testdata (or at least mocked testdata). In fact you use Mockito to keep dependencies of your tests out, so you can test the code that your application uses and to "ignore" dependencies of third party test environments.

duffy356
  • 3,678
  • 3
  • 32
  • 47