Interview Questions

Can You Write a JUnit Test Case Class in 10 Minutes?

JUnit Questions and Answers


(Continued from previous question...)

Can You Write a JUnit Test Case Class in 10 Minutes?

Here is a good JUnit test case class example that you should be able to write within 10 minutes. This example is provided by Varun Chopra and valid for JUnit 3.8.

Assuming that Java class DirLister.java has following three methods and one variable:

  • String dirPath - Member variable that represents directory in use
  • createLogFile(String fileName) - Member method that creates a file in dirPath
  • exists(String fileName) - Member method that checks the existence of a file within dirPath
  • getChildList() - Member method that gets the list of files and directories within dirPath

We want to test above three methods with Junit. For that, we will create another Java class that will have the test code for these three methods. See the class below:

/*
 * DirListerTest.java
 * JUnit based test
 *
 * Created on May 26, 2005, 11:33 AM
 */
package javaegs.junit;

import java.io.File;
import java.io.IOException;
import junit.framework.*;
/**
 * @author varunc
 */

public class DirListerTest extends TestCase {

 DirLister dl;

 /**
 * Test of createLogFile method, of class 
 javaegs.junit.DirLister.
 */

 public void testCreateLogFile() {
  dl = new DirLister("D:/temp/junittestdir");
  dl.createLogFile("logFile.log");
  assertTrue("File does not exist",dl.exists("logFile.log"));
 }

 /**
 * Test of exists method, of class 
 javaegs.junit.DirLister.
 */

 public void testExists() { 
  dl = new DirLister("D:/temp/junittestdir");
  assertTrue("File does not exist",dl.exists("logFile.log"));
 }

 /**
 * Test of getChildList method, of class 
 javaegs.junit.DirLister.
 */

 public void testGetChildList() {
  dl = new DirLister("D:/temp/junittestdir");
  String[] files = null;
  try {
   files = dl.getChildList();
  } catch(Exception ex) {
   fail("Exception occured"+ex);
   ex.printStackTrace();
   }
  assertNotNull("Children can't be null",files);
  assertTrue("No. of files can't be 0",files.length>0);
 }

/**
 * @param args the command line arguments
 */
 public static void main(String[] args) {
 junit.textui.TestRunner.run(DirListerTest.class); 
 }
}

(Continued on next question...)

Other Interview Questions