Showing posts with label Maven2. Show all posts
Showing posts with label Maven2. Show all posts

Wednesday, February 11, 2009

Writing Test Cases with JUnit

JUnit is one of the most famous test case development frameworks for Java programmers.

It is also easy to integrate into Eclipse IDE.

If your projest is Maven enabled, then just by adding JUnit dependencies in your project's pom.xml file, you will be able to start generating test cases for your project. Add this dependency in your project's pom.xml file.
 
   junit
   junit
   3.8.2 
 

Save your pom.xml file and it will start downloading JUnit jar file into your Maven repository.

It is a good practice to place your test cases into the same project with your classes to be tested.

So create a folder named with "src/test/java" into your project and create a new package into it which is going to contain your JUnit test cases.

After adding Junit jar file and creating a folder which is going to contain your test cases, your directory structure is going to look like in Eclipse as follows.

eclipse project with junit dependency


Now add your class to be tested into org.junit.sample package.

Assume that, you are reading a flat file from your local disk containing mobilePhone number, id number and startDate of Employees separated by semicolon ";" .

Your simple Employee.java class contains:
package org.junit.sample;
import java.util.Date;
public class Employee {

 public Employee(){
 }
 String mobilePhone;
 String IdNumber;
 Date startDate;
 public String getMobilePhone() {
  return mobilePhone;
 }
 public void setMobilePhone(String mobilePhone) {
  this.mobilePhone = mobilePhone;
 }
 public String getIdNumber() {
  return IdNumber;
 }
 public void setIdNumber(String idNumber) {
  IdNumber = idNumber;
 }
 public Date getStartDate() {
  return startDate;
 }
 public void setStartDate(Date startDate) {
  this.startDate = startDate;
 } 
}


Sample file (Employee_Data) content is as follows, each line contains 3 significant parts separated by ";" :

3452701678;44522445566;12.09.2008 09:34:10
2133223914;56705003122;12.09.2008 10:36:31

and it is located at your home folder.

Java class that is required to be tested is a class that reads contents of the above text file and parses it to store each element of it's lines in an Employee object.

Simple FileService.java class which is located in the same package with Employee.java is as follows :
package org.junit.sample;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileService {

 public FileService(){
 }
 
 public Boolean parseTextFile(){
  String readFileFrom = "Employee_Data";
  String strLine,dateTime;
  String[] strArr= new String[3];
  
  File file = null;
  FileInputStream fstream = null;
  DataInputStream dataInputStream = null;
  BufferedReader br = null;
  
  Employee employee = null;
  List<Employee> list = null;
  DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
  Date date;
  try {
   file = new File(readFileFrom);   
   fstream = new FileInputStream(file);
   dataInputStream = new DataInputStream(fstream);
   br = new BufferedReader(new InputStreamReader(dataInputStream));
   list = new ArrayList<Employee>();
   while ((strLine = br.readLine()) != null) {
         System.out.println (strLine);
         strArr = strLine.split(";");
         employee = new Employee();
         employee.setMobilePhone(strArr[0]);
         employee.setIdNumber(strArr[1]);
         dateTime = strArr[2];
         date = (Date)formatter.parse(dateTime);
         employee.setStartDate(date);
         list.add(employee);
         employee = null;
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }
  if(list != null && list.size() > 0)
   return true;
  else
   return false;
 }
}

Related test case is located in the same Maven enabled project under "/src/test/java" folder. 


FileServiceTest.java class extends from junit framework's TestCase class. testparseTextFile() method in FileServiceTest.java class is used to test FileService.java class's parseTextFile() method.



package org.junit.sample.test;
import org.junit.sample.FileService;
import junit.framework.TestCase;

public class FileServiceTest extends TestCase {
 public FileServiceTest(){
 }
 public void testparseTextFile() throws Exception {
         Boolean readFileResult = false;
  FileService fileService = new FileService();
  readFileResult = fileService.parseTextFile();
  assertTrue(readFileResult);
 }
}



In order to start debugging your FileServiceTest.java class, right click on the name of the test method that you want to run from Outline view of Eclipse and then from the context menu choose :
Debug As -> JUnit Test.


eclipse run junit test case in debug mode



It is not taking long time to prepare Eclipse for JUnit test case development. 

Writing test cases efficiently decreases the amount of time spent for development and testing of your application.

Saturday, January 31, 2009

Generate Excel Files with Apache POI

Apache POI is a useful API to work with MS Excel files using Java.

It is capable of reading and writing Excel files with formatted cells.

You can extract a new Excel file by reading data from an existing Java entity to a specified location.

If you are using Apache Maven as your dependency management tool then add POI as a dependency into your project's pom.xml file.

Save your pom.xml file and then Eclipse will immediately update related Maven dependencies to your local Maven repository.

 poi
 poi
 2.5.1

After adding the above dependency in your project, under Maven dependencies you will see poi.jar file.

Also, create a Java entity class to use as a data holder which is named with Employee.java in the same package.

package org.sample.apachepoi;

public class Employee {

 private String name;
 private String surName;
 private String telNumber;
 private Long salary;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSurName() {
  return surName;
 }
 public void setSurName(String surName) {
  this.surName = surName;
 }
 public String getTelNumber() {
  return telNumber;
 }
 public void setTelNumber(String telNumber) {
  this.telNumber = telNumber;
 }
 public Long getSalary() {
  return salary;
 }
 public void setSalary(Long salary) {
  this.salary = salary;
 } 
}


Create a service class "ApachePoiSample.java" which contains operations to write an Excel file.


ApachePoiSample.java class methods









Outline of the ApachePoiSample class is represented at above. "generateExcelFiles" method is used to write Excel files to a specified location.


eclipse project with apache poi dependency

















After adding Apache Poi Maven dependency and creating a new Java Project, file structure is displayed in Eclipse IDE as in the image at above. 

You can change the location of the dependencies that are stored on your hard drive by modifying the settings.xml file for Maven.

To change the location of local Maven repository add these lines into your settings.xml file : 

Eclipse->Preferences->Maven->Installations->User Settings

clicking the Browse button will take you to the maven settings.xml file.

add your local repository in to the settings.xml file by adding "localrepository" node which contains the new repository location such as "/home/UserName/.m2/repository "
"generateExcelFiles" method is used to write new Excel files.

public void generateExcelFiles(List<Employee> employee){
  
  HSSFWorkbook wb;
  HSSFSheet sheet;
  OutputStream out;
  String fileName,fileExtension,fileLocation;

  if(employee != null && employee.size()>0){
  
   wb = new HSSFWorkbook();
   sheet = wb.createSheet("EmployeeData");
   prepareWorkBook(wb, sheet);
   fileLocation = "/home/tufangorel/";
   fileName = "Employee WorkSheet";
   fileExtension = ".csv";
   for (int j = 0; j < employee.size(); j++) {
    HSSFRow newRow = sheet.createRow((short) j + 1);
    createCell(employee,j,newRow);
   }
   try {
    out = new FileOutputStream(fileLocation+fileName+fileExtension);
    wb.write(out);
    out.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 } 


In order to create an Excel document add HSSFWorkBook and HSSFSheet objects into your method. 


HSSFRow object represents each row in the Excel file. "createCell" method takes a single employee record and copies that data into a new HSSFRow object.



private void createCell(List<Employee> list,int j, HSSFRow newRow) {
  if (list.get(j).getName() != null && !list.get(j).getName().equals("")) {
 newRow.createCell((short) 0).setCellValue(list.get(j).getName());
  }
  if (list.get(j).getSurName() != null && !list.get(j).getSurName().equals("")) {
 newRow.createCell((short) 1).setCellValue(list.get(j).getSurName());
  }
  if (list.get(j).getTelNumber() != null && !list.get(j).getTelNumber().equals("")) {
 newRow.createCell((short) 2).setCellValue(list.get(j).getTelNumber());
  }
  if (list.get(j).getSalary() != null) {
 newRow.createCell((short) 3).setCellValue(list.get(j).getSalary());
  }
}


"prepareWorkBook" method creates the first line, header line for the Excel file.


HSSFCellStyle and HSSFFont objects are required to make style modifications to Excel sheet.

private void prepareWorkBook(HSSFWorkbook wb, HSSFSheet sheet) {
  HSSFRow row = sheet.createRow((short) 0); 
  HSSFFont font = wb.createFont();    
  font.setColor(HSSFFont.BOLDWEIGHT_BOLD);
  font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  HSSFCellStyle cellStyle = wb.createCellStyle(); 
  cellStyle.setFont(font);
  createHeaderCellsFormatting(row, cellStyle); 
}


"createHeaderCellsFormatting" method writes the names of columns in your sheet and set cell style.

private void createHeaderCellsFormatting(HSSFRow row,HSSFCellStyle cellStyle) {
 row.createCell((short) 0).setCellValue("Name");
 HSSFCell cell0 = row.getCell((short) 0);
 cell0.setCellStyle(cellStyle);
 row.createCell((short) 1).setCellValue("SurName");
 HSSFCell cell1 = row.getCell((short) 1);
 cell1.setCellStyle(cellStyle);
 row.createCell((short) 2).setCellValue("Tel Number");
 HSSFCell cell2 = row.getCell((short) 2);
 cell2.setCellStyle(cellStyle);
 row.createCell((short) 3).setCellValue("Salary");
 HSSFCell cell3 = row.getCell((short) 3);
 cell3.setCellStyle(cellStyle);  
}


in order to test your ApachePoiSample class add a main method which creates Employee objects and calls "generateExcelFiles" method to see the extracted Excel at the specified location.


public static void main(String[] args) {
  
 List<Employee> employee = new ArrayList<Employee>();
 Employee e1 = new Employee();
 e1.setName("John");
 e1.setSalary(2000L);
 e1.setSurName("Blade");
 e1.setTelNumber("1233873");
 employee.add(e1);
 Employee e2 = new Employee();
 e2.setName("Mary");
 e2.setSalary(3000L);
 e2.setSurName("New");
 e2.setTelNumber("343222");
 employee.add(e2);  
 ApachePoiSample apachePoiSample = new ApachePoiSample();
 apachePoiSample.generateExcelFiles(employee);
}