6

I am new to Mockito and I have started to learn it. But I have some questions. Why do we need to use Mockito? As far as I know it is used to Mock(Create dummy object) and write the test cases before having actual running code. But, what if I want to test my already implemented code to check whether they are functioning properly or not. How would I test it using Mockito?

For instance, I have CRUD methods and I would like to test whether Create is functioning properly by actually inserting data in database using my Create method, similarly for others. Can we attain it using Mockito. If not, then do I need to write different testcases for them without using Mockito?

Ravi Nain
  • 605
  • 8
  • 16
  • 10
    You never mock the Class Under Test (the CUT). You mock it's _dependencies_. If you're testing CRUD methods, you don't want to have to create a database, populate it with data, create a connection pool, supply a connection, etc. You just provide a `mock(Connection.class)` and verify that the your `update()` method invokes the behaviour on the `Connection` in the appropriate manner. To reiterate, you **never mock the CUT**. – Boris the Spider Oct 09 '16 at 11:32
  • And just wondering: did you read any documentation / tutorial about Mokito to learn about it? It rather seems that your first idea was to drop a way-too-broad question here. – GhostCat Oct 09 '16 at 19:00
  • Possible duplicate of [What is Mocking?](http://stackoverflow.com/questions/2665812/what-is-mocking) – kryger Oct 09 '16 at 19:02
  • Related - http://stackoverflow.com/q/12539365 – Dawood ibn Kareem Oct 14 '16 at 10:57

1 Answers1

14

The Mock is used to each class or service you are using. The class under test should not be Mocked. Lets assume you are connecting to a remote service which is being built by one of your engineering team, and you are not familiar with its internal functionality but you know what requests and response it returns. In that case, you can create a Mock of that Object, and defines it with set of responses returns in different situations. Each situation should get its own different test and for each response you should check separately the reaction of the code (you are working on).

Another great example is creating a limitation checks. Lets think of exception that might be thrown in some situations. You can Mock the object that will throw the Exception which is simple(~2-3 line of test code if you are using Mock) and you can check how the code you have written reacts to that Exception. Without the Mock the throwing of an exception might be really complicated thing and not so easy to use if you are not familiar with the small details. And of course the Mock enables you to be on focus of the main functionality you are checking cause it make the checking time very very small. And that is a bless when time to market is a critical thing.

Rotem
  • 1,381
  • 1
  • 11
  • 23