Table of contents
1.
Introduction
2.
Test Case
2.1.
Program
2.2.
Program
2.3.
Program
2.4.
Program
3.
Mockito
3.1.
Program
4.
EasyMock
4.1.
Program
5.
Mockito vs. EasyMock
5.1.
Test Spies Support
5.1.1.
Mockito Example
5.1.2.
Output
5.2.
Mocked Method Calls
5.3.
Verifying Calls
5.3.1.
Mockito Example
5.3.2.
Output
5.3.3.
EasyMock Example
5.3.4.
Output
5.4.
Mock Exception Throwing
5.4.1.
Mockito Example
5.4.2.
Output
5.4.3.
EasyMock Example
5.4.4.
Output
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Mockito vs. EasyMock

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In object-situated programming, mocking an object allows us to fake its behavior to isolate some other object depending on this behavior more fully. In an ideal scenario, a unit test should test only one class. And mocking is the best practice of testing an object linked to other objects.

Mockito and EasyMock are two of the most popular mocking frameworks available in Java programming. These frameworks can easily collaborate with any testing frameworks available in Java, such as JUnit, to perform unit tests.

This article will take you through the basic concepts, implementations, and differences between Mockito and EasyMock with the help of some examples.

Test Case

We will set up an elementary test case for the examples that we will use in this article. 

We will start with the UserForm class that will hold the username and password.

Program

//src/main/java/com.codingninjas.testrunner/UserForm.java
package com.codingninjas.testrunner;


public class UserForm {


    public String password;


    public String username;


    public String getUsername() {
        return username;
    }


}
You can also try this code with Online Java Compiler
Run Code

Next, we will create a void functionality(LoginDao), so we can mock its method when we need it.

Program

//src/main/java/com.codingninjas.testrunner/LoginDao.java


package com.codingninjas.testrunner;


public class LoginDao {


    public int login(UserForm userForm) {
        return 0;
    }
}
You can also try this code with Online Java Compiler
Run Code

Our next class(LoginService) will use the LoginDao for its login method and have a setCurrentUser method returning void to test that mocking.

Program

//src/main/java/com.codingninjas.testrunner/LoginService.java
package com.codingninjas.testrunner;


public class LoginService {


    private LoginDao loginDao;


    @SuppressWarnings("unused")
    private String currentUser;


    public boolean login(UserForm userForm) {
        assert null != userForm;


        int loginResults = loginDao.login(userForm);


        switch (loginResults) {
            case 1:
                return true;
            default:
                return false;
        }
    }


    public void setCurrentUser(String username) {
        if (null != username) {
            this.currentUser = username;
        }
    }


    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
}
You can also try this code with Online Java Compiler
Run Code

Finally, the LoginController class we are creating will use our LoginService class for its login method. This class will include multiple cases.

Program

//src/main/java/com.codingninjas.testrunner/LoginController.java
package com.codingninjas.testrunner;


public class LoginController {


    public LoginService loginService;


    public String login(UserForm userForm) {
        //if no calls to the mocked service are done.
        //if only one method are called.
        //if all methods are called.
        //if exception throwing is tested.
        if (null == userForm) {
            return "ERROR";
        } else { 
            boolean logged;


            try {
                logged = loginService.login(userForm);
            } catch (Exception e) {
                return "ERROR";
            }


            if (logged) {
                loginService.setCurrentUser(userForm.getUsername());
                return "OK";
            } else {
                return "KO";
            }
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Mockito

Mockito is an open-source Java-based mocking framework delivered under the MIT license. The framework allows you to create test double objects in automated unit tests for test-driven development or behavior-driven development.

Often, We use Mockito to mock interfaces to add a dummy functionality to a mock interface that we can use for unit testing. For the examples in this article, we will use Mockito version 2.

The setup for our test code using Mockito and JUnit in the examples we will use in this article looks like this.

Program

//src/test/java/com.codingninjas.testrunner/LoginControllerMockito.java
package com.codingninjas.testrunner;



import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;


public class LoginControllerIntegrationTestMockito {


    @Mock
    private LoginDao loginDao;


    @Spy
    @InjectMocks
    private LoginService spiedLoginService;


    @Mock
    private LoginService loginService;


    @InjectMocks
    private LoginController loginController;


    @Before
    public void setUp() {
        loginController = new LoginController();
        MockitoAnnotations.initMocks(this);
    }
…
}
You can also try this code with Online Java Compiler
Run Code

EasyMock

Like Mockito, EasyMock is also an open-source Java-based mocking framework released under the Apache license. EasyMock is very similar to Mockito when it comes to functionality. It also has the primary purpose of allowing us to create test double objects in automated unit tests for test-driven development or behavior-driven development.

The setup for our test code using EasyMock and JUnit in the examples we will use in this article will look like this.

Program

//src/test/java/com.codingninjas.testrunner/LoginControllerEasyMock.java
package com.codingninjas.testrunner;


import org.easymock.*;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;


@RunWith(EasyMockRunner.class)
public class LoginControllerIntegrationTestEasyMock {


    @Mock
    private LoginDao loginDao;


    @Mock
    private LoginService loginService;


    @TestSubject
    private LoginController loginController = new LoginController();
…
}
You can also try this code with Online Java Compiler
Run Code

Mockito vs. EasyMock

Despite the apparent similarities in the core functionality of Mockito and EasyMock, there are some critical differences in the implementation, features, and methods of these two mocking frameworks. We will now take a look at some of these differences with the help of some examples.

Test Spies Support

One of the vital differences between Mockito and EasyMock is that Mockito supports spies and mocks. Whereas EasyMock does not support spies. 

Spy and Mocks have different functionality. A Spy is also known as a partial mock because it partially mocks an object and uses the real implementation instead of mocked method calls in a few of its methods. On the other hand, a Mock creates a dummy object that is wholly mocked.

In our test setup for Mockito, we have created a spy and a mock for our LoginService. So instead of using .thenCallRealMethod() in a typical mock method call definition, we use a spy for partial mocking in our test. When we use a spy instead of a mock, the default behavior will be to call the real implementation in all non-mocked methods.

Mockito Example

    @Test
    public void partialMocking() {
        // using partial mock
        loginController.loginService = spiedLoginService;
        UserForm userForm = new UserForm();
        userForm.username = "foo";
        // let service's login use implementation so it let's mock DAO call
        Mockito.when(loginDao.login(userForm))
            .thenReturn(1);


        String login = loginController.login(userForm);


        Assert.assertEquals("OK", login);
        // verify the mocked call
        Mockito.verify(spiedLoginService)
            .setCurrentUser("foo");
    }
You can also try this code with Online Java Compiler
Run Code

Output

Mocked Method Calls

In Mockito, you can use .when(mock.method(args)).thenReturn(value) for mocking method calls. You can also return different values for more than one call by adding them as parameters like thenReturn(value1, value2, value-n, …).

In EasyMock, you can use .expect(mock.method(args)).andReturn(value) for mocking method calls.

In the next section, we will see the example for both implementations.

Verifying Calls

For verifying calls in Mockito, you can use Mockito.verify(mock).method(args). You can also use Mockito.verifyNoMoreInteractions(mock) to verify that Mockito did no more calls.

You can also pass specific values or use predefined matchers like any(), anyString(), or anyInt() for verifying arguments.

In the example below, we will mock method call and then use verify() to verify the call to our mock service.

Mockito Example

    @Test
    public void assertTwoMethodsHaveBeenCalled() {
        UserForm userForm = new UserForm();
        userForm.username = "foo";
        Mockito.when(loginService.login(userForm))
            .thenReturn(true);


        String login = loginController.login(userForm);


        Assert.assertEquals("OK", login);
        Mockito.verify(loginService)
            .login(userForm);
        Mockito.verify(loginService)
            .setCurrentUser("foo");
    }
You can also try this code with Online Java Compiler
Run Code

Output

In EasyMock, you can use EasyMock.verify(mock) for verifying calls to your mock. Remember that you must always call it after calling EasyMock.replay(mock).

You can also pass specific values, or predefined matchers like isA(Class.class)anyString(), or anyInt() to verify arguments in EasyMock. 

You can see the implementation of mocked method and verifying calls to that mock using EasyMock below.

EasyMock Example

    @Test
    public void assertTwoMethodsHaveBeenCalled() {
        UserForm userForm = new UserForm();
        userForm.username = "foo";
        EasyMock.expect(loginService.login(userForm)).andReturn(true);
        loginService.setCurrentUser("foo");
        EasyMock.replay(loginService);


        String login = loginController.login(userForm);


        Assert.assertEquals("OK", login);
        EasyMock.verify(loginService);
    }
You can also try this code with Online Java Compiler
Run Code

Output

Mock Exception Throwing

Another vital feature of Mockito and Easy mock is that they allow you to mock Exception Throwing.

In Mocktio, you can mock Exception Throwing by using .thenThrow(ExceptionClass.class) after a Mockito.when(mock.method(args)) like in the example below.

Mockito Example

    @Test
    public void mockExceptionThrowing() {
        UserForm userForm = new UserForm();
        Mockito.when(loginService.login(userForm))
            .thenThrow(IllegalArgumentException.class);


        String login = loginController.login(userForm);


        Assert.assertEquals("ERROR", login);
        Mockito.verify(loginService)
            .login(userForm);
        Mockito.verifyNoMoreInteractions(loginService);
    }
You can also try this code with Online Java Compiler
Run Code

Output

In EasyMock, using andThrow(new ExceptionClass()) after an EasyMock.expect() call is the way to mock exception throwing, as shown in the example below.

EasyMock Example

    @Test
    public void mockExceptionThrowing() {
        UserForm userForm = new UserForm();
        EasyMock.expect(loginService.login(userForm)).andThrow(new IllegalArgumentException());
        EasyMock.replay(loginService);


        String login = loginController.login(userForm);


        Assert.assertEquals("ERROR", login);
        EasyMock.verify(loginService);
    }
You can also try this code with Online Java Compiler
Run Code

Output

Frequently Asked Questions

  1. What is the difference between mock and spy?
    While we can use both mock or spy to mock methods or fields, there is a difference in their implementation and functionality. In mock, we are creating a complete mock or fake object, and in spy, there is the real object, and we are just spying or stubbing specific methods of it. When we use mock objects, the default behavior of the method when not stub is to do nothing, while the default behavior using spy is to use the real implementation of all the non-mocked methods.
     
  2. What is stubbing and mocking?
    Like mocking, stubbing means creating a stand-in. But the difference between a stub and a mock is that a stub only mocks the behavior and not the entire object. You can use this when your implementation only interacts with a particular behavior of the object.
     
  3. Should we use Mockito spy?
    In general scenarios, if you want to be safe and just check the logic inside a unit while avoiding calling external services, it is recommended to use a mock instead of a spy. You should use a spy if you want to run the program as it is and just stub some particular methods or call an external service and real dependencies.
     
  4. What are matchers in Mockito?
    Matchers are like regex or wildcards, where instead of specifying a specific input and or output, we define we can verify a range or type of input/output based on which stubs/spies can be rest and calls to stubs. 
    All the Mockito matchers are a part of the 'Mockito' static class.

Conclusion

In this article, we have extensively discussed the key differences and concepts of Mockito and EasyMock and their implementation in unit testing using JUnit and Java programming. There are many more features and distinctions in implementing both of these mocking frameworks that you will come across as you start working extensively with these tools.

We hope this blog has helped you enhance your knowledge regarding mocking and unit testing in Java. If you would like to learn more, check out our articles on  JUnit Introduction and FeaturesJUnit Environment Setup and Framework, and Basics of Java. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass