Using mockito in Java

Source: Internet
Author: User

If you 've spent any time writing unit tests then you'll know that it's not always straight-forward. certain things are inherently hard to test. in this post I'll show you the basic principles of creating mock objects with a little help from the mockito mocking
Tool.

One common problem faced when unit testing is how to test one object when it is dependant on another object. you cocould create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is
Not what unit testing is about-unit tests shocould test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won't work if the dependent object hasn' t even been implemented yet.

A common technique for handling dependencies in unit tests is to provide a surrogate, or "mock" object, for the dependent object instead of a real one. the mock object will implement a simplified version of the real objects methods that return predictable results
And can be used for testing purposes.

The drawback of this approach is that in a complex application, you cocould find yourself creating a lot of mock objects. This is where frameworks like mockito can save you a of lot time and effort.
A test scenario

To demonstrate what you can do with mockito, we'll examine how we might test an account object that is dependant on a data access object (accountdao ). the account object can calculate the charges applicable in the current month by using the DAO to count
Number of days overdrawn and then should Ming a simple calculation on the value obtained from that call. The method names on the classes we'll use are self-explanatory:

Accountanddao
To test this thoroughly, We shoshould test two things:

1. That the account obtains the number of overdrawn days by calling the correct method on the Dao,
2. That the account calculates the correct fees based upon the value it gets back from the call.

Testing that the account callthe correct method on the Dao

Using JUnit to run the test case, We coshould write something like this:
01. Import static org. mockito. mockito .*;
02.
03. Public class testaccount {
04. @ Test
05. Public void checkaccountcallsdaomethods (){
06. // create the object under test
07. Account account = new account ();
08.
09. // create a mock Dao
10. accountdao mockeddao = mock (accountdao. Class );
11.
12. // associate the mocked Dao with the object under test
13. Account. setdao (DAO );
14.
15. // call the method under test
16. Long charge = Account. calculatecharges ();
17.
18. // verify that the 'countoverdrawndaysthismonth' was called
19. Verify (mockeddao). countoverdrawndaysthismonth ();
20 .}
21 .}

Taking center stage in all this is the mockito class which has a bunch of static methods that are used within the unit test (note the static import on Line 1 ).

The call to the 'mock 'method (Line 10) creates a mock object that can be used in place of a real accountdao. the call to 'verify '(line 19), will throw an exception if the 'countoverdrawndaysthismonth' method was not called on the mock object.

It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.
Testing that the account performs its calculations correctly

In the above example, We mocked the Dao but didn't specify what any of the mocked Methods shoshould do. in this case, all methods will return sensible default values of: NULL, zero or false. more commonly we need to specify something other than these defaults
When writing our tests:
01. Import static org. mockito. mockito .*;
02. Import static JUnit. Framework. Assert .*;
03. Import org. JUnit .*;
04.
05. Public class testaccount {
06. Private Account account;
07.
08. @ before
09. Public void setup (){
10. accountdao mockeddao = mock (accountdao. Class );
11.
12. // specify that this method on the mock object shocould return 8
13. When (mockeddao. countoverdrawndaysthismonth (). thenreturn (8 );
14.
15. Account = new account ();
16. Account. setdao (DAO );
17 .}
18.
19. @ Test
20. Public void checkchargeswhenoverdrawn (){
21. // call the method under test
22. Long charge = Account. calculatecharges ();
23.
24. // assert that the charge was £2 per day overdrawn
25. assertequals (charge, 16 );
26 .}
27 .}

The statement on line 18 specifies that whenever the 'countoverdrawndaysthismonth 'is called it shoshould return a value of 8; overriding the default of zero.

Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account has med the correct calculation (8x2 = 16 right ).
Comments

There's loads more to mockito than we 've looked at here. it's a neat testing tool that works great with JUnit or testng. I 've found that it's small enough to learn quickly and capable enough to be really useful. give it a go and write a comment below to let
Me know what you think of it

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.