Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

JUnit and Mockito cooperation

This time I want to make an overview of testing framework Mockito. Definitely this is one of the most popular tools for the testing of java code. I have already made the overview of the Mockito’s competitor – EasyMock. This post will be based on the sample application from the post about EasyMock. I mean classes which represent coffee machine functionality.

Preparation of testing with Mockito

As usually I will use Maven for the project setup. So to make Mockito available in the project, I need to add following dependency in the pom.xml file:
 

	<dependencies>
		<dependency>
			<groupid>org.mockito</groupid>
			<artifactid>mockito-all</artifactid>
			<version>1.9.5</version>
		</dependency>
		<dependency>
			<groupid>junit</groupid>
			<artifactid>junit</artifactid>
			<version>4.11</version>
		</dependency>
	</dependencies>

Notice that JUnit isn’t required for the normal functionality of Mockito, you can use in the same way TestNG instead of it. So you can use either JUnit or TestNG depending on your decision.

Let’s move further. As I mentioned earlier, all tests in this article will be written for the sample application from the post about EasyMock. You can read just “Application code” section from there. That will be enough to understand the subject of the testing.

Mockito & JUnit tests

I want to start this section with a couple of sentences about the Mockito framework. Definitely with the help of Mockito you can do everything you wish in the testing. You can create mocks, stubs, make verifications and all this with the help of clear API.
It’s time to see how unit tests with Mockito look like.
 
 

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.app.data.Portion;
import com.app.exceptions.NotEnoughException;
import com.app.mechanism.CoffeeMachine;
import com.app.mechanism.interfaces.ICoffeeMachine;
import com.app.mechanism.interfaces.IContainer;

@RunWith(MockitoJUnitRunner.class)
public class CoffeeMachineTest {

	ICoffeeMachine coffeeMachine;

	@Mock
	IContainer coffeeContainer;
	@Mock
	IContainer waterContainer;

	@Before
	public void setUp() {
		coffeeMachine = new CoffeeMachine(coffeeContainer, waterContainer);
	}

	@After
	public void tearDown() {
		coffeeContainer = null;
		waterContainer = null;
		coffeeMachine = null;		
	}

	@Test
	public void testMakeCoffe() throws NotEnoughException {

		when(coffeeContainer.getPortion(Portion.LARGE)).thenReturn(true);
		when(waterContainer.getPortion(Portion.LARGE)).thenReturn(true);

		assertTrue(coffeeMachine.makeCoffee(Portion.LARGE));
	}

	@Test
	public void testNotEnoughException() throws NotEnoughException {

		when(coffeeContainer.getPortion(Portion.SMALL)).thenReturn(false);
		when(waterContainer.getPortion(Portion.SMALL)).thenReturn(true);

		assertFalse(coffeeMachine.makeCoffee(Portion.SMALL));

	}

}

I will explain in a few words, what’s going on in the test class. I’m testing the coffee machine and for this purpose I create mocks for the coffee container and water container. Further in the tests I will define some behavior for the mocks, and depending on this coffee machine will perform expected actions.

...
	@Mock
	IContainer coffeeContainer;
	@Mock
	IContainer waterContainer;
...

In the code above I declared two mocks. Creation of the mocks in this way requires @RunWith(MockitoJUnitRunner.class) annotation applied to the test class. As the alternative you can use MockitoAnnotations.initMocks(testClass); before any test will run, e.g. you can put this code snippet in the method annotated with @Before.

...
when(coffeeContainer.getPortion(Portion.LARGE)).thenReturn(true);
...

Defining mock’s behavior in the Mockito performs in a very convenient manner. You specify what should be returned after the particular method was called. Notice that I have made several static imports in the test class.

Summary

Mockito framework has conquered my heart. It’s very convenient, its API is clear, usage is laconic. Mockito contains a lot of methods which can be needed during the unit tests development. Of course one post is too small to describe all features of Mockito, so I recommend you to dig deeper using follow link to the official documentation.
 

Reference: JUnit and Mockito cooperation from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


7 + = fifteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.