Vyoms OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Bookmark and Share Rss Feeds

Unit Testing with Spring | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Sponsored Ads
Hot Jobs
Fresher Jobs
Experienced Jobs
Government Jobs
Walkin Jobs
Placement Section
Company Profiles
Interview Questions
Placement Papers
Resources @ VYOMS
Companies In India
Consultants In India
Colleges In India
Exams In India
Latest Results
Notifications In India
Call Centers In India
Training Institutes In India
Job Communities In India
Courses In India
Jobs by Keyskills
Jobs by Functional Areas
Learn @ VYOMS
GATE Preparation
GRE Preparation
GMAT Preparation
IAS Preparation
SAP Preparation
Testing Preparation
MBA Preparation
News @ VYOMS
Freshers News
Job Articles
Latest News
India News Network
Interview Ebook
Get 30,000+ Interview Questions & Answers in an eBook.
Interview Success Kit - Get Success in Job Interviews
  • 30,000+ Interview Questions
  • Most Questions Answered
  • 5 FREE Bonuses
  • Free Upgrades

VYOMS TOP EMPLOYERS

Wipro Technologies
Tata Consultancy Services
Accenture
IBM
Satyam
Genpact
Cognizant Technologies

Home » Articles » Unit Testing with Spring

Unit Testing with Spring








Article Posted On Date : Monday, September 6, 2010


Unit Testing with Spring
Advertisements

In a system with multiple components, Unit testing mandates that each component works fine individually. Various factors that are ensured at this stage are whether the functionality provided by the various methods (private and public) are correct in terms of passing arguments and handling of exceptions. As an example, let us assume there are User and UserGroupclasses . User is dependant on UserGroup object, whereas UserGroup is not dependant on User. In this scenario, we have to make sure that User and UserGroupclasses are working individually to the expected extent.

Mock objects come into picture in the case of dependant objects. Let us assume that there is a class called UserService which is dependant on UserDao object. UserDao class takes care of hitting the database for performing CRUD operations. In this case, it is also not possible that the UserDao class be available during the early stages of development for the simple reason that the database environment may not be available. In such cases, we mock the implementation of UserDaoclasses. Spring Framework supports such mocking facility for almost all the classes that cannot be tested. For example, let us take the example of a Servlet that parses and returns the request information back to the client. After writing the Servlet, it is impossible to test the Servlet in stand-alone mode, the only way to test it would be starting a Web Container and then invoking a client that can initiate HTTP requests.

This may not be ideal for all scenarios, as for every change done to the Servlet, the Servlet has to be re-deployed (hot deployment can be used if the Container supports) it. Let us jump into an example to see how Mockclasses come to the rescue. We will develop a Controler using Spring framework that accepts an account information and returns a view containing the various details related to the account such as the account name, customer name etc..

Account Info

AccountInfo.java

package net.javabeat.spring.articles.testing.mock.web.controller;

public class AccountInfo {

private String accountId;

private String customerName;
private String customerNumber;
private String debitCardNumber;

public AccountInfo(String customerName, String customerNumber, String debitCardNumber){

this.customerName = customerName;
this.customerNumber = customerNumber;
this.debitCardNumber = debitCardNumber;
}

public String getAccountId() {
return accountId;
}

public void setAccountId(String accountId) {
this.accountId = accountId;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public String getCustomerNumber() {
return customerNumber;
}

public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}

public String getDebitCardNumber() {
return debitCardNumber;
}

public void setDebitCardNumber(String debitCardNumber) {
this.debitCardNumber = debitCardNumber;
}

}

The above class represents AccountInfo model object containing details ike the account id, name of the customer, id of the customer etc. To make the system more interesting, we will throw an Invalid Account Id Exception when the account id is invalid (that is, the account id is not present in the database).

Invalid Account Id Exception

InvalidAccountIdException.java

package net.javabeat.spring.articles.testing.mock.web.controller;

public class InvalidAccountIdException extends Exception{

/**
* Default serial version UID
*/
private static final long serialVersionUID = 1L;

public InvalidAccountIdException(String message){
super(message);
}
}

It is mandatory that the client has to pass the account id to the Controller so that the account details can be displayed. Given below is an Application exception that will be thrown when the account id is not passed from the client.

Null Account Id Exception

NullAccountIdException.java

package net.javabeat.spring.articles.testing.mock.web.controller;

public class NullAccountIdException extends Exception{

/**
* Default serial version UID
*/
private static final long serialVersionUID = 1L;

public NullAccountIdException(String message){
super(message);
}
}

Now here comes the Controller class that handles the core logic. Initially it checks for the account id as part of the request, if it is not present, then an Application exception is thrown. Then it checks whether the account id is legal by checking from the existing list of accounts. Then it constructs a Model and View object with the desired inputs.

Account Info Web Controller

AccountInfoWebController.java

package net.javabeat.spring.articles.testing.mock.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class AccountInfoWebController extends AbstractController{

private static Map&t;String, AccountInfo> mapOfAccounts;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

String accountId = getAccountId(request);
if (accountId == null){
throw new NullAccountIdException("Account Id is invalid or empty");
}

if (!mapOfAccounts.containsKey(accountId)){
throw new InvalidAccountIdException("Account Id is invalid");
}

AccountInfo accountInfo = mapOfAccounts.get(accountId);
ModelAndView accountInfoMV = new ModelAndView("accountInfoView", "accountInfoModel", accountInfo);
return accountInfoMV;
}

private static String getAccountId(HttpServletRequest request){

try {
return ServletRequestUtils.getStringParameter(request, "ACCOUNT_ID");
} catch (ServletRequestBindingException e) {
e.printStackTrace();
return null;
}
}

static{
mapOfAccounts = new HashMap&t;String, AccountInfo>();

mapOfAccounts.put("12345", new AccountInfo("Jerry", "12345", "67890"));
mapOfAccounts.put("23456", new AccountInfo("Jefrey", "23456", "78901"));
}
}

Note that without the support of Mock classes, the only way to test this Controller, is by deploying this component as part of a Web Application, then starting the Sever and then by initiating a Http client on the running server. It is also impossible to create an instance of the aboveController object and then call its handleRequest() method because of dependencies.

Account Info Web Controller Test

AccountInfoWebControllerTest.java

package net.javabeat.spring.articles.testing.mock.web.controller;

import java.util.Iterator;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.ModelAndViewAssert;
import org.springframework.web.servlet.ModelAndView;

public class AccountInfoWebControllerTest {

private AccountInfoWebController controller;

@Before
public void init(){

controller = new AccountInfoWebController();
}

@Test
public void test1() throws Exception{

MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");

MockHttpServletResponse response = new MockHttpServletResponse();
try{
controller.handleRequest(request, response);
Assert.fail("Should have thrown Null Account Id Exception");
}catch (NullAccountIdException exception){
}catch (Exception exception){
Assert.fail(exception.getMessage());
}
}

@Test
public void test2() throws Exception{

MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.addParameter("ACCOUNT_ID", "11111");

MockHttpServletResponse response = new MockHttpServletResponse();
try{
controller.handleRequest(request, response);
Assert.fail("Should have thrown Invalid Account Id Exception");
}catch (InvalidAccountIdException exception){
}catch (Exception exception){
Assert.fail(exception.getMessage());
}
}

@SuppressWarnings("unchecked")
@Test
public void test3() throws Exception{

MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.addParameter("ACCOUNT_ID", "12345");

MockHttpServletResponse response = new MockHttpServletResponse();
try{

ModelAndView modelAndView = controller.handleRequest(request, response);
Assert.assertNotNull(modelAndView);

ModelAndViewAssert.assertAndReturnModelAttributeOfType(modelAndView, "accountInfoModel", AccountInfo.class);
ModelAndViewAssert.assertViewName(modelAndView, "accountInfoView");

Iterator&t;String> iterator = modelAndView.getModel().keySet().iterator();
if (iterator.hasNext()){

String key = iterator.next();
AccountInfo accountInfo = (AccountInfo)modelAndView.getModel().get(key);

Assert.assertEquals("Jerry", accountInfo.getCustomerName());
Assert.assertEquals("12345", accountInfo.getCustomerNumber());
Assert.assertEquals("67890", accountInfo.getDebitCardNumber());
}else{
}
}catch (Exception exception){
Assert.fail(exception.getMessage());
}
}

@After
public void destroy(){
controller = null;
}
}






Sponsored Ads



Interview Questions
HR Interview Questions
Testing Interview Questions
SAP Interview Questions
Business Intelligence Interview Questions
Call Center Interview Questions

Databases

Clipper Interview Questions
DBA Interview Questions
Firebird Interview Questions
Hierarchical Interview Questions
Informix Interview Questions
Microsoft Access Interview Questions
MS SqlServer Interview Questions
MYSQL Interview Questions
Network Interview Questions
Object Relational Interview Questions
PL/SQL Interview Questions
PostgreSQL Interview Questions
Progress Interview Questions
Relational Interview Questions
SQL Interview Questions
SQL Server Interview Questions
Stored Procedures Interview Questions
Sybase Interview Questions
Teradata Interview Questions

Microsof Technologies

.Net Database Interview Questions
.Net Deployement Interview Questions
ADO.NET Interview Questions
ADO.NET 2.0 Interview Questions
Architecture Interview Questions
ASP Interview Questions
ASP.NET Interview Questions
ASP.NET 2.0 Interview Questions
C# Interview Questions
Csharp Interview Questions
DataGrid Interview Questions
DotNet Interview Questions
Microsoft Basics Interview Questions
Microsoft.NET Interview Questions
Microsoft.NET 2.0 Interview Questions
Share Point Interview Questions
Silverlight Interview Questions
VB.NET Interview Questions
VC++ Interview Questions
Visual Basic Interview Questions

Java / J2EE

Applet Interview Questions
Core Java Interview Questions
Eclipse Interview Questions
EJB Interview Questions
Hibernate Interview Questions
J2ME Interview Questions
J2SE Interview Questions
Java Interview Questions
Java Beans Interview Questions
Java Patterns Interview Questions
Java Security Interview Questions
Java Swing Interview Questions
JBOSS Interview Questions
JDBC Interview Questions
JMS Interview Questions
JSF Interview Questions
JSP Interview Questions
RMI Interview Questions
Servlet Interview Questions
Socket Programming Interview Questions
Springs Interview Questions
Struts Interview Questions
Web Sphere Interview Questions

Programming Languages

C Interview Questions
C++ Interview Questions
CGI Interview Questions
Delphi Interview Questions
Fortran Interview Questions
ILU Interview Questions
LISP Interview Questions
Pascal Interview Questions
Perl Interview Questions
PHP Interview Questions
Ruby Interview Questions
Signature Interview Questions
UML Interview Questions
VBA Interview Questions
Windows Interview Questions
Mainframe Interview Questions


Copyright © 2001-2024 Vyoms.com. All Rights Reserved. Home | About Us | Advertise With Vyoms.com | Jobs | Contact Us | Feedback | Link to Us | Privacy Policy | Terms & Conditions
Placement Papers | Get Your Free Website | IAS Preparation | C++ Interview Questions | C Interview Questions | Report a Bug | Romantic Shayari | CAT 2024

Fresher Jobs | Experienced Jobs | Government Jobs | Walkin Jobs | Company Profiles | Interview Questions | Placement Papers | Companies In India | Consultants In India | Colleges In India | Exams In India | Latest Results | Notifications In India | Call Centers In India | Training Institutes In India | Job Communities In India | Courses In India | Jobs by Keyskills | Jobs by Functional Areas

Testing Articles | Testing Books | Testing Certifications | Testing FAQs | Testing Downloads | Testing Interview Questions | Testing Jobs | Testing Training Institutes

Gate Articles | Gate Books | Gate Colleges | Gate Downloads | Gate Faqs | Gate Jobs | Gate News | Gate Sample Papers | Gate Training Institutes

MBA Articles | MBA Books | MBA Case Studies | MBA Business Schools | MBA Current Affairs | MBA Downloads | MBA Events | MBA Notifications | MBA FAQs | MBA Jobs
MBA Job Consultants | MBA News | MBA Results | MBA Courses | MBA Sample Papers | MBA Interview Questions | MBA Training Institutes

GRE Articles | GRE Books | GRE Colleges | GRE Downloads | GRE Events | GRE FAQs | GRE News | GRE Training Institutes | GRE Sample Papers

IAS Articles | IAS Books | IAS Current Affairs | IAS Downloads | IAS Events | IAS FAQs | IAS News | IAS Notifications | IAS UPSC Jobs | IAS Previous Question Papers
IAS Results | IAS Sample Papers | IAS Interview Questions | IAS Training Institutes | IAS Toppers Interview

SAP Articles | SAP Books | SAP Certifications | SAP Companies | SAP Study Materials | SAP Events | SAP FAQs | SAP Jobs | SAP Job Consultants
SAP Links | SAP News | SAP Sample Papers | SAP Interview Questions | SAP Training Institutes |


Copyright ©2001-2024 Vyoms.com, All Rights Reserved.
Disclaimer: VYOMS.com has taken all reasonable steps to ensure that information on this site is authentic. Applicants are advised to research bonafides of advertisers independently. VYOMS.com shall not have any responsibility in this regard.