JUnit test with Mockito and Spring

It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to other enterprise infrastructure.

This could be done in your Spring project by using Spring-test library and Mockito framework.


Photo credit: Honey

In this post, I present a simple way to create a mock and to inject it into a tested bean.

Preparation of testing with Mockito

To make Mockito available, we need to add following dependency in the pom.xml file.


Deveop Mockito, Spring and JUnit tests

The code source bellow presents a JUnit test using Spring-test and Mockito framework.

  • @RunWith(SpringJUnit4ClassRunner.class) runs the test with Spring custom runner that will load Spring application context.
  • @Autowire associate invoiceService reference to the InvoiceService instance.
  • @Before annotation executes the setup method before the test.
  • MockitoAnnotations.initMocks(this) scans the class annotation, instanciates invoiceDaoMock and inject it into the InvoiceService bean.
  • when(.(any())).thenReturn() associates a return value with method execution parameters.

import static org.mockito.Mockito.*; 

//Load Spring contexte
@ContextConfiguration(locations = {"classpath:/application-context.xml"})
public class InvoiceServiceTest {
	// Create Mock
	private IInvoiceDao invoiceDaoMock;
	private IInvoiceService invoiceService;
	public void setUp() {

	public void testProcessInvoice() throws SQLException {
		// specify mock behave when method called
		Map<Product, Integer> products = new HashMap<Product, Integer>();
		products.put(new Product("labtop", BigDecimal.valueOf(1255.50)), 2);
		Invoice invoice = invoiceService.processInvoice(products);
		Assert.assertEquals(1255.50 * 2, invoice.getTotal().doubleValue(), 0);

17 thoughts on “JUnit test with Mockito and Spring

  1. Can you send me your application-context.xml file? I want to see how you are mocking EntityManagerFactory.

    1. Hi,

      In this sample the DAO is mocked. The real save (or others DAO methods are not executed). For this reason we don’t need to mock EntityManagerFactory.

      There are no special or specific things in application-context.xml. It’s some thing like the code bellow.

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="……………………………>
      <context:component-scan base-package="com.mycompany.project" />
      <bean id="entityManagerFactory"
      <property name="dataSource" ref="dataSource" />
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      <tx:annotation-driven />
      <bean id="transactionManager" class="….JpaTransactionManager" >
      <property name="entityManagerFactory" ref="entityManagerFactory" />

  2. Where is the interest to use spring in this example ?
    more generally, is spring needed with mockito ?

  3. Is this code compilable? What is ti “when” and “any” identifiers. It looks like method name, but no methods of these names are defined in this example.

  4. This doesn’t work for me. The invoiceDaoMock isn’t injected into invoiceService. Instead it tries to make call to the actual dao method. I am unable to figure out what am i missing out here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s