Wednesday, 17 September 2014

Mockito Tutorial -Part2 . Spring and Mockito Integration.

In the below example we use Calcuator Obect which computes the area of Rectangle using Rectangle Objects.

Frame works used

  • Spring -Dependency Injection
  • Mockito- Mocking java Obejcts
  • JUnit- Unit Test frame work. 

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.lac.tut.mockito.Calculator;
import com.lac.tut.mockito.Rectangle;

@ContextConfiguration(locations = { "classpath:/beans.xml" })
public class CalculatorTestWithSpringAndMockito {

 Rectangle rectangle;

 Calculator calculator;

 public void create() {
  initMocks(this);// Initialize this mock objects

 public void test() {
  assertEquals(calculator.getArea(), 400);


Explanation: In the above example the mocked rectangle object is injected into calculator object. @InjectMocks annotation of Mockito inject mocked rectangle object into calculator bean. The annotation @RunWith makes the class is runned with SpringJUnit4ClassRunner. The annotation ContextConfiguration specifies the path of spring bean definition.
package com.lac.tut.mockito;

public class Calculator {
 private Rectangle rectangle;

 public Rectangle getRectangle() {
  return rectangle;

 public void setRectangle(Rectangle rectangle) {
  this.rectangle = rectangle;

 public int getArea() {
  return rectangle.getLength() * rectangle.getBreadth();

package com.lac.tut.mockito;

public class Rectangle {
 public int length;
 public int breadth;

 public int getLength() {
  return length;

 public void setLength(int length) {
  this.length = length;

 public int getBreadth() {
  return breadth;

 public void setBreadth(int breadth) {
  this.breadth = breadth;




Download the source code of above tutorial at :

No comments:

Post a Comment