Tag Archives: java

A dive into Mockito – 3

Part 3 - Partial Mocks using Mockito and Limitations of Mockito

  • Partial Mocks – with mocks and spies
  • Create a mock of the class
  • Spy the class
  • Which method to use – mock or spy?
  • Limitations of Mockito

Full Series

Partial Mocks – with mocks and spies

Partial mocks are created when only some methods of a class need to be stubbed, and the real methods must be called for others.

Partial mocks can be created in two ways:

  1. Create a mock of the class
    This would create mock implementation of all the methods. For calling the real method, we must use thenCallRealMethod()
  2. Spy the class
    This is the opposite of creating mocks. This will call real methods, unless otherwise specified by stubs.

Let us consider EmailManager.java having a method: String getEmail(String name)

Create a mock of the class

Partial mocks can be created in the following manner by creating mocks:

EmailManager managerMock = Mockito.mock(EmailManager.class);

This will call the real implementation of getEmail() method in the EmailManager. The mock implementations will be called for all other methods.

Spy the class

This is the method to create spies of real objects:

EmailManager manager = new EmailManager();
EmailManager managerSpy = Mockito.spy(manager);

This will call the stubbed implementation of getEmail() method in the EmailManager. The real implementation will be called for all other methods

Exception when spying:

While spying, remember that the actual methods are called. This can cause a lot of side effects, and sometimes Exceptions.

The primary reason for this is that the method call inside when() actually gets executed. So, even if the method is stubbed, it can internally call another method of the class which might not be stubbed, and the real method will be called.

The below code would fail:

List list = new LinkedList();
List spy = Mockito.spy(list);

A closer look at the stacktrace shows something like this:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
  at java.util.LinkedList.entry(LinkedList.java:368)
  at java.util.LinkedList.get(LinkedList.java:313)

The get(0) internally calls entry() method(), which is not stubbed, causing the real method to be called.

To prevent this error, an alternative syntax must be used:


Which method to use – mock or spy?

To decide which method to use, take a look at how many methods need to be stubbed.

  • If more real methods need to be called, then use spy.
  • Otherwise, use mock

New, well-designed and test-driven code should not use partial mocks. Using partial mocks means that the actual code is badly designed. But that should not stop us from writing unit tests.

A bad unit test is better than no unit test.

Limitations of Mockito

Mockito has a few limitations

  • Cannot mock final classes
  • Cannot mock static methods
  • Cannot mock final methods – their real behaviour is executed without any exception. Mockito cannot warn you about mocking final methods, so be vigilant.
  • Cannot mock equals(), hashCode()

Future articles in the series:

  • Part 4 – Some complex examples and common mistakes in using Mockito

A dive into Mockito – 2

Part 2 – Argument Matchers and Stubbing Void Methods

  • Using Argument Matchers
  • A simple use of any() matcher
  • Writing Custom Argument Matchers
  • Stubbing void methods

Full Series

Using Argument Matchers

Mockito argument matchers can be used to specify the method arguments for stubbing. If the method has arguments but you really don’t care what gets passed or cannot predict it, argument matchers can be used.

Argument Matchers provide us a lot of flexibility in stubbing.

Argument Matchers use the equals() method for comparisons.

A simple use of any() matcher

Let us assume we have an EmailService that is trying to save an email ID using an EmailManager. This means that the save() method of the EmailService calls the save() method of the EmailManager, which in turn saves the email to the database. A simple unit test for the save() method of the EmailService can test whether the save() on the Manager was called.

import org.junit.Test;
import org.mockito.Mockito;

public class EmailServiceTest {
	public void testSaveEmail() {
		EmailManager manager = Mockito.mock(EmailManager.class);
		EmailService service = new EmailService(manager);



Note the use of the argument matcher in line 12:


We used the matcher because, we really do not care what parameter was passed on the save().

The generic any() matcher:

Mockito provides a matcher that matches any Object. Some valid variants of the above are:


The cast from Object to String is required in the first line, the lack of which will cause compilation error.

The second line shown above is most useful when we need to match custom classes we create in our application.
Assuming save() method saves a Person object, we would write:


While using argument matchers in stubbing, all arguments of a method must be matchers.

If our save method also takes in an integer, this line would throw error:

Mockito.verify(manager).save(12, Mockito.any(Person.class));

To fix the above scenario, we can write:

Mockito.verify(manager).save(Mockito.eq(12), Mockito.any(Person.class));

Some common Argument Matchers

any() or any(Class clazz)Any object (or object of a given class) or null

Any object of given type or null
eqDefault Matcher. Compares using equals() method
sameObject argument that is the same as the given value. Compares using ==
refEqObject argument that is reflection-equal to the given value. This Matcher can be used when equals() is not implemented on compared objects. Matcher uses Java reflection API to compare fields of wanted and actual objects.
Argument is null/not null
contains(String substring)
matches(String regex)
endsWith(String suffix)
startsWith(String prefix)
String-specific argument matchers

Writing Custom Argument Matchers

Consider this scenario. We have the following classes:

  • Person – A class with two variables – name, email id
  • PersonService – A service class that creates a Person object and calls savePerson() method on the manager
  • PersonManager – The manager class that needs to be mocked

We need to write test case for personLogic() method in PersonService


public class PersonService {
	private final PersonManager manager;

	public PersonService(PersonManager manager) {
		this.manager = manager;

	public void personLogic() {
		Person person = new Person("Karthik", "abc@xyz.com");

The below test will fail:

import org.junit.Test;
import org.mockito.Mockito;

public class PersonServiceTest {
	public void testPersonLogic() {
		PersonManager manager = Mockito.mock(PersonManager.class);
		PersonService service = new PersonService(manager);


		Person verifyPerson = new Person("Karthik", "abc@xyz.com");

Reason: The expected object, with reference verifyPerson is entirely different from the actual object, and the default equals() comparison which argument matchers use, fails.

Use Custom Argument Matcher

In this scenario, using custom argument matchers come in handy.

Lines 12 and 13 above can be replaced with this:

				Mockito.argThat(new ArgumentMatcher() {

					public boolean matches(Object argument) {
						Person person = (Person) argument;
						return person.getName().equals("Karthik")
								&& person.getEmail().equals("abc@xyz.com") ? true
								: false;

Alternate Solution – 1

Use the refEq matcher to compare the fields of the objects in hand:

Person verifyPerson = new Person("Karthik", "abc@xyz.com");

Alternate Solution – 2

Override the equals() method in Person class to compare objects.

Stubbing void methods

We face a lot of scenarios in our applications where we need to stub void methods. With void methods, stubbing is slightly different. We cannot use void methods in the when() call.

The alternative syntax is:


We can also test exception handling. How would my code handle if an exception is thrown by void methods

Mockito.doThrow(new RuntimeException()).when(mock).setAttribute(Mockito.anyString());

We can also set the behaviour of a void method to do nothing when called. This is not possible for non-void methods:


Why when() does not work for void methods:

Take a look at the syntax of when():


Notice that the method is called inside brackets. Compiler does not like void method inside brackets!!

The two ‘when()’ are different syntax.

Notice that the when() for a non-void method stubbing takes in a methodCall as parameter, whereas the when() in void method stubbing takes in a mock object.

doPrimarily used for stubbing void methods
doThrow(Throwable... throwables).when(mock).method();
doReturn(T value).when(mock).method();
doAnswer(Answer answer).when(mock).method();

Future articles in the series:

  • Part 3 – Partial Mocks using Mockito and Limitations of Mockito
  • Part 4 – Some complex examples and common mistakes in using Mockito

A dive into Mockito – 1

Part 1 – Getting Started with Mockito

  • Mocking Frameworks – Mockito
  • A simple use of Mockito
  • Verifying Interactions with the mock
  • Stubbing methods using when()

Full Series

Mocking Frameworks

Mocking Frameworks allow us to test the code you want, without its dependencies. In a unit test, mock objects can simulate the behaviour of complex objects that are impractical or impossible to incorporate into a unit test.

Mock objects isolate the unit of code you are testing.


This is a framework used for test stubbing and interaction testing.

Let us assume that we have a simple servlet, and a method testCheckFormat() that checks the format of the email id submitted in the HTML form. It is impractical to create an actual HttpServletRequest object for unit test. So we mock this object, in order to test the code we are interested in.

A simple use of Mockito

import javax.servlet.http.HttpServletRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class ServletFacadeTest {

	public void testCheckFormat() {
		HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);

		ServletFacade servletFacade = new ServletFacade();
		boolean result = servletFacade.checkFormat(requestMock);

		Assert.assertEquals(true, result);

There are three fundamental steps in writing JUnit test cases with Mockito:

  1. Create a mock of the object on which the method under test is dependent [line 10]
  2. Specify behaviors on the mock object (stub) [line 11]
  3. Assert/verify test scenario [lines 14-16]

Verifying Interactions with the mock

One of the most important capabilities of Mockito is to verify whether the mock had any interactions. A mock object will remember all its invocations.

The following test would have passed in the above case:


It is also easy to ensure that there were no more interactions with our mock apart from getting the email:


Let’s assume that our logic now tries retrieving two details from the request, namely email and name. To test two invocations, we now can use:


We can write this slightly differently, using argument matchers provided by Mockito:

Mockito.verify(requestMock, Mockito.times(2)).getAttribute(Mockito.anyString());

Verifying a stubbed invocation is unnecessary and often leads to just redundant tests!

verify( T mock).someMethod();
verify( T mock, times(int n) ).someMethod();
verify( T mock, atLeast(int n) ).someMethod();
verify( T mock, atLeastOnce() ).someMethod();
verify( T mock, atMost(int n) ).someMethod();
verify( T mock, never() ).someMethod();
Verify that someMethod was called specified number of times. Default is once.
verifyZeroInteractions( Object... mocks );Verify that there have been no method calls on the mock object(s)
verifyNoMoreInteractions( Object... mocks )Verify that there have been no additional method calls on the mock object(s) besides what has already been verified.

Stubbing methods using when()

Stubbing is used to specify method behaviors on mock objects.
We have already seen an example of stubbing:


Argument matchers can be used in stubs to match the invocation with any specified argument:
In the below example, any invocation of getAttribute() with a String parameter will return the string “xyz@abc.com”.


Sometimes, we might have to test exception handling. How would my code handle if an exception is thrown by getAttribute()

Mockito.when(requestMock.getAttribute(Mockito.anyString())).thenThrow(new RuntimeException());

when() would work only for non-void methods!

whenOnly for non-void methods
when( mock.method() ).thenCallRealMethod();
when( mock.method() ).thenReturn(T value);
when( mock.method() ).thenReturn(T value, T... values);
when( mock.method() ).thenThrow(Throwable... throwables);
when( mock.method() ).thenAnswer(Answer answer);

This should get you started with some basic unit tests with Mockito. Have fun !! :)

Future articles in the series:

  • Part 2 – Argument Matchers and stubbing void methods
  • Part 3 – Partial Mocks using Mockito and Limitations of Mockito
  • Part 4 – Some complex examples and common mistakes in using Mockito

Java Java jing-jing-jing … !

This song makes me love Java even more I normally do !!!

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jing

It’s not a cup of coffee but it’s hot as can be
Came pourin’ through the Gates on a “Big Mac” Nealy
Singin’, Java, Java, Java Java jing-jing-jing

Microsoft thought Java really could be a threat
Java through the Windows maybe put them in debt
Gates, he took a license but he altered the feel
Java members all said, “Bill, you’re outta the deal!”
Singin’, Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jing

It’s like a cup of coffee ’cause it’s tasty and fresh
But it’s not really Java if the flavours don’t mesh
Pure Java, Java, Java Java jing-jing-jing

Microsoft released a browser, Java was there
The Sun, it rose and lit up what was really a dare
The RMI, the JNI were missing and lost
Scott said, “Bill, you broke your promise, Now pay the cost!”
Bill said, “Hey, my recipe is richer than yours”
Scott said, “I own the coffee shop, sit down and I’ll pour”
Pour Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jing

Nobody can tell yet what the future may bring
All we know is Java goes jing-jing-jing
It goes Java, Java, Java Java jing-jing-jing
(Scott really means it)
Java, Java, Java Java jing-jing-jing
(Bill you better believe it)
Java, Java Java jing-jing-jing

Download the song here:
Java Posse Jingle

This song is the intro music of Java Posse podcast, written and performed in 1997 by Loose Bruce Kerr of the Dr. Demento Show and Sun Microsystems attorney.

“Nobody can tell yet what the future may bring” …. 13 years ago !!!


software freedom week – java workshop

After one full week of preparation, giving lectures and handling lab classes, the Java programming workshop has finally come to an end. The workshop was conducted by me with the help of my friend, Aswin, as a part of Software Freedom Week celebrations.

This was the first workshop conducted in college by me after I was selected as the Campus Ambassador for Sun Microsystems. Java is one of the greatest products from Sun, which is extensively used in programming, web applications, mobile applications and more. So, I felt that conducting a workshop on Java programming would help the students learn the language. The workshop was intended to show the students the door to the world of Java.

The curriculum of NITT does not have an exclusive Java course. But there are many students who are interested in learning the language. I have seen many friends of mine who have tried to learn Java, but were confused about where to start and how to proceed.

The workshop was planned for second year B. Tech CSE students of my college. I went to their classroom and briefed them about the various open source technologies, about the Campus Ambassador Programme of Sun and about the numerous workshops that are to follow in the months to come. I also asked the students to do a study on open source and write an article on the same. The response was very good.

My HOD arranged the conference hall and the laboratory for our use. With the help of Aswin, I installed Java and Netbeans in all computers in the lab. The projector was set up too. The stage was set for the workshop.

32 students had been selected for the workshop. Everyone had assembled, eagerly awaiting the start. I distributed the Netbeans CDs, pens and key chains which Sun Microsystems had sent for the workshop. Then the classes began.

We started right from the basics, explaining the simple looping constructs, the conditional statements and various other syntax. Then we moved on to object oriented programming and related concepts like abstraction and polymorphism. Concepts of classes and objects were explained with regular demos on screen.

When Aswin was handling the class, I was busy taking snaps. Our HOD also visited the class to make sure everything was running smoothly.

java classes
The workhshop in progress at conference hall
The presentation on screen
The class... HOD is seen too

We then explained the concepts of streams used in input/output. Exception handling was taught in detail. The lab practice sessions were interesting. Some students came up with excellent solutions which even we never thought of. The workshop was a learning experience for us too.

We also conducted a small review  examination to gauge the understanding of the participating candidates. We wrote a simple Java program to evaluate the answers of students. The answers were discussed later.

That's me..
Netbeans loading in one of the computers
The lab session

We then ventured into complex topics like networking and swt. Students were taught how to write a chat application. They also had a lab session on that, where they implemented chat application and file sending programmes.

Practice makes a programmer perfect. Learning from the book will not help in learning a language. To become an expert, one must practice various programs and develop programming skills. This was emphasized during the workshop.

During the workshop, we asked the students to look up some interesting topics online, like obfuscated code and the dining philosophers problem. This helped the students to learn loads of new stuff.

All the presentations used and the demo programs were mailed to the students. The students’ feedback on the programme was also overwhelming. On the last day, I requested the students to look beyond text books and the curriculum. There must be a thirst for knowledge. Everyone must participate in the development of open source technologies. Gone is the age when there was a divide between the developer and the user. Now is the age where the user is the developer.

The first Java workshop was thus completed successfully. I am planning for the next workshop, which might be on Opensolaris, one of the most stable operating systems from Sun Microsystems. Looking forward to learning and sharing…