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.


CalculatorTestWithSpringAndMockito.java 
 
package test.com.lac.tut.mockito;

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" })
@RunWith(SpringJUnit4ClassRunner.class)
public class CalculatorTestWithSpringAndMockito {

 @Mock
 Rectangle rectangle;

 @InjectMocks
 @Autowired
 Calculator calculator;

 @Before
 public void create() {
  initMocks(this);// Initialize this mock objects
  when(rectangle.getLength()).thenReturn(10);
  when(rectangle.getBreadth()).thenReturn(40);
 }

 @Test
 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.


Calculator.java
 
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();
 }

}


Rectangle.java
 
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;
 }

}


beans.xml
 


 
 
 
  
 
 
 
  
  
 
 



Download the source code of above tutorial at : http://www.luckyacademy.com/downloads.html




No comments:

Post a Comment