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.

//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);

About these ads
This entry was posted in Java, test framework, Uncategorized and tagged , , , , , , . Bookmark the permalink.

8 Responses to JUnit test with Mockito and Spring

  1. Clean and Simple. Thank you.

  2. I love you for this. You showed me a simple solution and saved a lot of time. Thanks for coming up in google.

  3. Really good and practical. I’ve never merged Spring with Junit and Mockito together in one code before.
    Thank you very much for sharing it

  4. Sandy says:

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

    • 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" />

  5. pankaj says:

    Thanks buddy…

  6. srikanth says:

    It’s saved my day..

  7. bawan says:

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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s