DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. 5 Minute Mockito

5 Minute Mockito

Alex Collins user avatar by
Alex Collins
·
Sep. 10, 10 · Tutorial
Like (1)
Save
Tweet
Share
75.88K Views

Join the DZone community and get the full member experience.

Join For Free

Some might find EasyMock a little frustrating and perhaps even too convoluted - here's a look at Mockito, a similar framework but with less complex use leading to quicker and simpler mock testing.

What is Mockito?

Apart from having a catchy name, Mockito attempts to think about mocking in a different way. Stated as an easy and lightweight alternative to EasyMock, Mockito is what you might call a Test Spy, and it seems to live up to all three of those ideologies. From its feature list, you can see it has a K.I.S.S approach (which I always like);

 Some other features:

  • Mocks concrete classes as well as interfaces
  • Little annotation syntax sugar - @Mock
  • Verification errors are clean - click on stack trace to see failed verification in test; click on exception's cause to navigate to actual interaction in code. Stack trace is always clean.
  • Allows flexible verification in order (e.g: verify in order what you want, not every single interaction)
  • Supports exact-number-of-times and at-least-once verification
  • Flexible verification or stubbing using argument matchers (anyObject(), anyString() or refEq() for reflection-based equality matching)
  • Allows creating custom argument matchers or using existing hamcrest matchers

One of my pet hates about EasyMock is its rather convoluted stacktraces when your mocks have failed or have been setup incorrectly. With Mockito, you are supposed to be able to get what you need from a failure - answers! Of course, there's only so much a framework can do; your tests need to be written properly in the first place, but we all do that, don't we?! 

A scenario

To demonstrate Mockito in a real-world example, we'll be mocking one interface. Below is DocumentRepository, whose FileBaseDocumentRepository implementation depends on a FileService instance (injected and the subject of our mock):

// package & import removed for brevitypublic interface DocumentRepository {    void addDocument(Document doc);    Document getDocument(DocumentID docId);}

And here's FileService, the class we'll be mocking (haha!) in our example:

// again, no packages or imports for brevitypublic interface FileService {    File createFile(String name);    File getFile(String name);    boolean fileExists(String filename);    boolean fileExists(File file);}

Brewing Mockito

In our FileBasedDocumentRepository implementation of DocumentRepository, we use the FileService to check if a file exists - via the fileExists(File f) method - and to get a file if so - via the getFile(File f) method. So, we need Mockito to do it's thing, and as you might expect we'd need to create our mocked instance by doing the following:

FileService fileService = mock(FileService.class);

Pretty easy stuff so far.

Next we'll need to tell the framework what to do when our two calls to FileService - fileExists and getFile - are made. To do so we use the when method:

when(fileService.fileExists(anyObject()));

Now we'll use our DocumentRepository and make an assertion using standard JUnit:

assertNull("Doc with non-existent name doesn't exist", docRepo.getDocument(doc.getID()));

 and finally we verify our mock calls:

verify(fileService);

So there you have it - a simple 5 minute introduction to Mockito. I recommend you read the Mockito wiki as it has a comparison of EasyMock amongst plenty of other things. Also, head on over to its feature list and FAQ pages or just download it.

Mockito

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Get Page Source in Selenium Using Python
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Agile Scrum and the New Way of Work in 2023
  • Top 12 Technical Skills Every Software Tester Must Have

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: