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.

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.1.2.RELEASE</version>
    <scope>test</scope>
</dependency>

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"})
@RunWith(SpringJUnit4ClassRunner.class)
public class InvoiceServiceTest {
	
	// Create Mock
	@Mock
	private IInvoiceDao invoiceDaoMock;
	
	@InjectMocks
	@Autowired
	private IInvoiceService invoiceService;
	
	
	@Before
	public void setUp() {
		MockitoAnnotations.initMocks(this);
	}

	
	@Test
	public void testProcessInvoice() throws SQLException {
		
		// specify mock behave when method called
		when(invoiceDaoMock.save(any(Invoice.class))).thenReturn(Long.valueOf(1));
		
		Assert.assertNotNull(invoiceService);
		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.

5 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"
      class="…..LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      …….
      </bean>
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      ………
      </bean>
      <tx:annotation-driven />
      <bean id="transactionManager" class="….JpaTransactionManager" >
      <property name="entityManagerFactory" ref="entityManagerFactory" />
      </bean>
      </beans>

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