Thursday, December 12, 2013

JUnit Framework


Q: What is testing?
A: Testing is the process of checking the functionality of the application whether it is working as per requirements.
Q: What is unit testing?
A: Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.
Q: What is Manual testing?
A: Executing the test cases manually without any tool support is known as manual testing.
Q: What is Automated testing?
A: Taking tool support and executing the test cases by using automation tool is known as automation testing.
Q: Out of Manual and Automated testing which one is better and why?
A: Manual Testing is:
  1. Time consuming and tedious.
  2. Huge investment in human resources.
  3. Less reliable.
  4. Non-programmable.
Automated testing is
  1. Fast
  2. Less investment in human resources
  3. More reliable
  4. Programmable
Q: What is JUnit?
A: JUnit is a unit testing framework for the Java Programming Language. It is written in Java and is an Open Source Software maintained by the JUnit.org community.
Q: What are important features of JUnit?
A: Import features of JUnit are:
  1. It is an open source framework.
  2. Provides Annotation to identify the test methods.
  3. Provides Assertions for testing expected results.
  4. Provides Test runners for running tests.
  5. JUnit tests can be run automatically and they check their own results and provide immediate feedback.
  6. JUnit tests can be organized into test suites containing test cases and even other test suites.
  7. JUnit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
Q: What is a Unit Test Case?
A: A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected. A formal written unit test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post condition.
Q: When are Unit Tests written in Development Cycle?
A: Tests are written before the code during development in order to help coders write the best code.
Q: Why not just use System.out.println() for testing?
A: Debugging the code using system.out.println() will lead to manual scanning of the whole output every time the program is run to ensure the code is doing the expected operations. Moreover, in the long run, it takes lesser time to code JUnit methods and test them on class files.
Q: How to install JUnit?
A: Follow the steps below:
  1. Download the latest version of JUnit, referred to below as junit.zip.
  2. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
  3. Add JUnit to the classpath:
    set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
  4. Test the installation by running the sample tests distributed with JUnit (sample tests are located in the installation directory directly, not the junit.jar file). Then simply type:
    java org.junit.runner.JUnitCore org.junit.tests.AllTests
    All the tests should pass with an "OK" message. If the tests don't pass, verify that junit.jar is in the CLASSPATH.
Q: Why does JUnit only report the first failure in a single test?
A: Reporting multiple failures in a single test is generally a sign that the test does too much and it is too big a unit test. JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test.
Q: In Java, assert is a keyword. Won't this conflict with JUnit's assert() method?
A: JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way. JUnit 4 is compatible with the assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit.
Q: How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?
A: Refactoring J2EE components to delegate functionality to other objects that don't have to be run in a J2EE container will improve the design and testability of the software. Cactus is an open source JUnit extension that can be used for unit testing server-side java code.
Q: What are JUnit classes? List some of them.
A: JUnit classes are important classes which are used in writing and testing JUnits. Some of the important classes are:
  1. Assert - A set of assert methods.
  2. TestCase - It defines the fixture to run multiple tests.
  3. TestResult - It collects the results of executing a test case.
  4. TestSuite - It is a Composite of Tests.
Q: What are annotations and how are they useful in JUnit?
A: Annotations are like meta-tags that you can add to you code and apply them to methods or in class. The annotation in JUnit gives us information about test methods , which methods are going to run before & after test methods, which methods run before & after all the methods, which methods or class will be ignore during execution.
Q: How will you run JUnit from command window?
A: Follow the steps below:
  1. Set the CLASSPATH
  2. Invoke the runner:
    java org.junit.runner.JUnitCore 
    
Q: What is JUnitCore class?
A: JUnitCore is an inbuilt class in JUnit package. It is based on Facade design pattern. This class is used to run only specified test classes.
Q: What is Test suite?
A: Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
Q: What is @Ignore annotation and how is this useful?
A: Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run. The @Ignore annotation helps in this regards. Following are some of the usefulness of @Ignore annotation:
  1. You can easily identify all @Ignore annotations in the source code, while unannotated or commented out tests are not so simple to find.
  2. There are cases when you can't fix a code that is failing, but you still want to method to be around, precisely so that it does not get forgotten. In such cases @Ignore makes sense.
Q: What are Parameterized tests?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How do you use test fixtures?
A: Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes:
  1. setUp() method which runs before every test invocation.
  2. tearDown() method which runs after every test method.
Q: How to compile a JUnit Test Class?
A: Compiling a JUnit test class is like compiling any other Java classes. The only thing you need watch out is that the JUnit JAR file must be included in the classpath.
Q: What happens if a JUnit Test Method is Declared as "private"?
A: If a JUnit test method is declared as "private", it compiles successfully. But the execution will fail. This is because JUnit requires that all test methods must be declared as "public".
Q: How do you test a "protected" method?
A: When a method is declared as "protected", it can only be accessed within the same package where the class is defined. Hence to test a "protected" method of a target class, define your test class in the same package as the target class.
Q: How do you test a "private" method?
A: When a method is declared as "private", it can only be accessed within the same class. So there is no way to test a "private" method of a target class from any test class. Hence you need to perform unit testing manually. Or you have to change your method from "private" to "protected".
Q: What happens if a JUnit test method is declared to return "String"?
A: If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is because JUnit requires that all test methods must be declared to return "void".
Q: How can you use JUnit to test that the code throws desired exception?
A: JUnit provides a option of tracing the Exception handling of code. You can test if a code throws desired exception or not. The expected parameter is used along with @Test annotation as follows: @Test(expected)
Q: What are Parameterized tests in JUnit?
A: Parameterized tests allow developer to run the same test over and over again using different values.
Q: How to create Parameterized tests?
A: There are five steps, which you need to follow to create Parameterized tests:
  1. Annotate test class with @RunWith(Parameterized.class).
  2. Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.
  3. Create a public constructor that takes in what is equivalent to one "row" of test data.
  4. Create an instance variable for each "column" of test data.
  5. Create your tests case(s) using the instance variables as the source of the test data.
The test case will be invoked once per each row of data.
Q: Can you use a main() Method for Unit Testing?
A: Yes you can test using main() method. One obvious advantage seems to be that you can whitebox test the class. That is, you can test the internals of it (private methods for example). You can't do that with unit-tests. But primarily the test framework tests the interface and the behavior from the user's perspective.
Q: Do you need to write a test class for every class that needs to be tested?
A: No. We need not write an independent test class for every class that needs to be tested. If there is a small group of tests sharing a common test fixture, you may move those tests to a new test class.
Q: When are tests garbage collected?
A: The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.


JUnit Tutorial

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with JUnit.
This tutorial will teach you how to use JUnit in your day-2-day life of any project unit testing while working with Java programming language.

Audience

This tutorial has been prepared for the beginners to help them understand basic functionality of JUnit tool. After completing this tutorial you will find yourself at a moderate level of expertise in using JUnit testing framework from where you can take yourself to next levels.

Prerequisites

We assume you are going to use JUnit to handle all levels of Java projects development. So it will be good if you have knowledge of software development using any programming language specially Java programming and software testing process.

Compile/Execute Java & JUnit Programs

For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.
Try following example using Try it option available at the top right corner of the below sample code box:
public class MyFirstJavaProgram {

    public static void main(String []args) {
       System.out.println("Hello World");
    }
} 


Testing is the process of checking the functionality of the application whether it is working as per requirements and to ensure that at developer level, unit testing comes into picture. Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.
Unit testing can be done in two ways
Manual testingAutomated testing
Executing the test cases manually without any tool support is known as manual testing.
  • Time consuming and tedious: Since test cases are executed by human resources so it is very slow and tedious.
  • Huge investment in human resources: As test cases need to be executed manually so more testers are required in manual testing.
  • Less reliable: Manual testing is less reliable as tests may not be performed with precision each time because of human errors.
  • Non-programmable: No programming can be done to write sophisticated tests which fetch hidden information.
Taking tool support and executing the test cases by using automation tool is known as automation testing.
  • Fast Automation runs test cases significantly faster than human resources.
  • Less investment in human resources:Test cases are executed by using automation tool so less tester are required in automation testing.
  • More reliable: Automation tests perform precisely same operation each time they are run.
  • Programmable: Testers can program sophisticated tests to bring out hidden information.

What is JUnit ?

JUnit is a unit testing framework for the Java Programming Language. It is important in the test driven development, and is one of a family of unit testing frameworks collectively known as xUnit.
JUnit promotes the idea of "first testing then coding", which emphasis on setting up the test data for a piece of code which can be tested first and then can be implemented . This approach is like "test a little, code a little, test a little, code a little..." which increases programmer productivity and stability of program code that reduces programmer stress and the time spent on debugging.

Features

  • JUnit is an open source framework which is used for writing & running tests.
  • Provides Annotation to identify the test methods.
  • Provides Assertions for testing expected results.
  • Provides Test runners for running tests.
  • JUnit tests allow you to write code faster which increasing quality
  • JUnit is elegantly simple. It is less complex & takes less time.
  • JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results.
  • JUnit tests can be organized into test suites containing test cases and even other test suites.
  • Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.

What is a Unit Test Case ?

A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected. To achieve those desired results quickly, test framework is required .JUnit is perfect unit test framework for java programming language.
A formal written unit test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a postcondition.
There must be at least two unit test cases for each requirement: one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative.


Try it Option Online

You really do not need to set up your own environment to start learning Java & JUnit programming language. Reason is very simple, we already have setup Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.
Try following example using Try it option available at the top right corner of the below sample code box:
public class MyFirstJavaProgram {

    public static void main(String []args) {
       System.out.println("Hello World");
    }
} 
For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.

Local Environment Setup

JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine.

System Requirement

JDK1.5 or above.
Memoryno minimum requirement.
Disk Spaceno minimum requirement.
Operating Systemno minimum requirement.

Step 1 - verify Java installation in your machine

Now open console and execute the following java command.
OSTaskCommand
WindowsOpen Command Consolec:\> java -version
LinuxOpen Command Terminal$ java -version
MacOpen Terminalmachine:~ joseph$ java -version
Let's verify the output for all the operating systems:
OSOutput
Windowsjava version "1.6.0_21" 
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Linuxjava version "1.6.0_21" 
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Macjava version "1.6.0_21" 
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK) fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.6.0_21 as installed version for this tutorial.

Step 2: Set JAVA environment

Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example
OSOutput
WindowsSet the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21
Linuxexport JAVA_HOME=/usr/local/java-current
Macexport JAVA_HOME=/Library/Java/Home
Append Java compiler location to System Path.
OSOutput
WindowsAppend the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of the system variable, Path.
Linuxexport PATH=$PATH:$JAVA_HOME/bin/
Macnot required
Verify Java Installation using java -version command explained above.

Step 3: Download Junit archive

Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-4.10.jar and copied it into C:\>JUnit folder.
OSArchive name
Windowsjunit4.10.jar
Linuxjunit4.10.jar
Macjunit4.10.jar

Step 4: Set JUnit environment

Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OSOutput
WindowsSet the environment variable JUNIT_HOME to C:\JUNIT
Linuxexport JUNIT_HOME=/usr/local/JUNIT
Macexport JUNIT_HOME=/Library/JUNIT

Step 5: Set CLASSPATH variable

Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OSOutput
WindowsSet the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;
Linuxexport CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.
Macexport CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.

Step 6: Test JUnit Setup

Create a java class file name TestJunit in C:\ > JUNIT_WORKSPACE
   
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
   @Test
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);
   }
}
Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}   

Step 7: Verify the Result

Compile the classes using javac compiler as follows
C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Now run the Test Runner to see the result
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.


What is Junit Test Framework?

JUnit is a Regression Testing Framework used by developers to implement unit testing in Java and accelerate programming speed and increase the quality of code. JUnit Framework can be easily integrated with either of the followings:
  • Eclipse
  • Ant
  • Maven

Features

JUnit test framework provides following important features
  • Fixtures
  • Test suites
  • Test runners
  • JUnit classes

Fixtures

Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes
  • setUp() method which runs before every test invocation.
  • tearDown() method which runs after every test method.
Let's check one example:
import junit.framework.*;

public class JavaTest extends TestCase {
   protected int value1, value2;
   
   // assigning the values
   protected void setUp(){
      value1=3;
      value2=3;
   }

   // test method to add two values
   public void testAdd(){
      double result= value1 + value2;
      assertTrue(result == 6);
   }
}

Test suite

Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. Here is an example which uses TestJunit1 & TestJunit2 test classes.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

//JUnit Suite Test
@RunWith(Suite.class)
@Suite.SuiteClasses({ 
   TestJunit1.class ,TestJunit2.class
})
public class JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit1 {

   String message = "Robert"; 
   MessageUtil messageUtil = new MessageUtil(message);
   
   @Test
   public void testPrintMessage() { 
      System.out.println("Inside testPrintMessage()");    
      assertEquals(message, messageUtil.printMessage());     
   }
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit2 {

   String message = "Robert"; 
   MessageUtil messageUtil = new MessageUtil(message);
 
   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Robert";
      assertEquals(message,messageUtil.salutationMessage());
   }
}

Test runner

Test runner is used for executing the test cases. Here is an example which assumes TestJunit test class already exists.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

JUnit classes

JUnit classes are important classes which is used in writing and testing JUnits. Some of the important classes are
  • Assert which contain a set of assert methods.
  • TestCase which contain a test case defines the fixture to run multiple tests.
  • TestResult which contain methods to collect the results of executing a test case.


    Now we'll show you a step by step process to get a kick start in Junit using a basic example.

    Create a Class

    • Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
    /*
    * This class prints the given message on console.
    */
    public class MessageUtil {
    
       private String message;
    
       //Constructor
       //@param message to be printed
       public MessageUtil(String message){
          this.message = message;
       }
          
       // prints the message
       public String printMessage(){
          System.out.println(message);
          return message;
       }   
    }  

    Create Test Case Class

    • Create a java test class say TestJunit.java.
    • Add a test method testPrintMessage() to your test class.
    • Add an Annotaion @Test to method testPrintMessage().
    • Implement the test condition and check the condition using assertEquals API of Junit.
    Create a java class file name TestJunit.java in C:\ > JUNIT_WORKSPACE
    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    public class TestJunit {
     
       String message = "Hello World"; 
       MessageUtil messageUtil = new MessageUtil(message);
    
       @Test
       public void testPrintMessage() {
          assertEquals(message,messageUtil.printMessage());
       }
    }

    Create Test Runner Class

    • Create a TestRunner java class.
    • Use runClasses method of JUnitCore class of JUnit to run test case of above created test class
    • Get the result of test cases run in Result Object
    • Get failure(s) using getFailures() methods of Result object
    • Get Success result using wasSuccessful() methods of Result object
    Create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestJunit.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    }   
    Compile the MessageUtil, Test case and Test Runner classes using javac
    C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
    
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner
    
    Verify the output.
    Hello World
    true
    
    Now update TestJunit in C:\ > JUNIT_WORKSPACE so that test fails. Change the message string.
    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    public class TestJunit {
     
       String message = "Hello World"; 
       MessageUtil messageUtil = new MessageUtil(message);
    
       @Test
       public void testPrintMessage() {
          message = "New Word";
          assertEquals(message,messageUtil.printMessage());
       }
    }
    Let's keep rest of the classes as is, and try to run same Test Runner
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestJunit.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    }
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner
    
    Verify the output.
    Hello World
    testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d>
    false
    
    
    
    

    Important API's of JUnit

    The most important package in JUnit is junit.framework which contain all the core classes. Some of the important class are
    Serial NoClass NameFunctionality
    1AssertA set of assert methods.
    2TestCaseA test case defines the fixture to run multiple tests.
    3TestResultA TestResult collects the results of executing a test case.
    4TestSuiteA TestSuite is a Composite of Tests.

    Assert Class

    Following is the declaration for org.junit.Assert class:
    public class Assert extends java.lang.Object
    This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are:
    S.N.Methods & Description
    1void assertEquals(boolean expected, boolean actual) Check that two primitives/Objects are equal
    2void assertFalse(boolean condition) Check that a condition is false
    3void assertNotNull(Object object) Check that an object isn't null.
    4void assertNull(Object object) Check that an object is null
    5void assertTrue(boolean condition) Check that a condition is true.
    6void fail() Fails a test with no message.
    Let's try to cover few of the above mentioned methods in an example. Create a java class file name TestJunit1.java in C:\ > JUNIT_WORKSPACE
    import org.junit.Test;
    import static org.junit.Assert.*;
    public class TestJunit1 {
       @Test
       public void testAdd() {
          //test data
          int num= 5;
          String temp= null;
          String str= "Junit is working fine";
    
          //check for equality
          assertEquals("Junit is working fine", str);
          
          //check for false condition
          assertFalse(num > 6);
    
          //check for not null value
          assertNotNull(str);
       }
    }
    Next, let's create a java class file name TestRunner1.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner1 {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestJunit1.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    }   
    Compile the Test case and Test Runner classes using javac
    C:\JUNIT_WORKSPACE>javac TestJunit1.java TestRunner1.java
    
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner1
    
    Verify the output.
    true
    

    TestCase Class

    Following is the declaration for org.junit.TestCaset class:
    public abstract class TestCase extends Assert implements Test
    A test case defines the fixture to run multiple tests. Some of the important methods of TestCase class are
    S.N.Methods & Description
    1int countTestCases() Counts the number of test cases executed by run(TestResult result).
    2TestResult createResult() Creates a default TestResult object.
    3String getName() Gets the name of a TestCase.
    4TestResult run() A convenience method to run this test, collecting the results with a default TestResult object.
    5void run(TestResult result) Runs the test case and collects the results in TestResult.
    6void setName(String name) Sets the name of a TestCase.
    7void setUp() Sets up the fixture, for example, open a network connection.
    8void tearDown() Tears down the fixture, for example, close a network connection.
    9String toString() Returns a string representation of the test case.
    Let's try to cover few of the above mentioned methods in an example. Create a java class file name TestJunit2.java in C:\ > JUNIT_WORKSPACE
    import junit.framework.TestCase;
    import org.junit.Before;
    import org.junit.Test;
    public class TestJunit2 extends TestCase  {
       protected double fValue1;
       protected double fValue2;
       
       @Before 
       public void setUp() {
          fValue1= 2.0;
          fValue2= 3.0;
       }
     
       @Test
       public void testAdd() {
          //count the number of test cases
          System.out.println("No of Test Case = "+ this.countTestCases());
      
          //test getName 
          String name= this.getName();
          System.out.println("Test Case Name = "+ name);
    
          //test setName
          this.setName("testNewAdd");
          String newName= this.getName();
          System.out.println("Updated Test Case Name = "+ newName);
       }
       //tearDown used to close the connection or clean up activities
       public void tearDown(  ) {
       }
    }
    Next, let's create a java class file name TestRunner2.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner2 {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestJunit2.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    } 
    Compile the Test case and Test Runner classes using javac
    C:\JUNIT_WORKSPACE>javac TestJunit2.java TestRunner2.java
    
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner2
    
    Verify the output.
    No of Test Case = 1
    Test Case Name = testAdd
    Updated Test Case Name = testNewAdd
    true
    

    TestResult Class

    Following is the declaration for org.junit.TestResult class:
    public class TestResult extends Object
    A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException. Some of the important methods of TestResult class are
    S.N.Methods & Description
    1void addError(Test test, Throwable t) Adds an error to the list of errors.
    2void addFailure(Test test, AssertionFailedError t) Adds a failure to the list of failures.
    3void endTest(Test test) Informs the result that a test was completed.
    4int errorCount() Gets the number of detected errors.
    5Enumeration<TestFailure> errors() Returns an Enumeration for the errors.
    6int failureCount() Gets the number of detected failures.
    7void run(TestCase test) Runs a TestCase.
    8int int runCount() Gets the number of run tests.
    9void startTest(Test test) Informs the result that a test will be started.
    10void stop() Marks that the test run should stop.
    Create a java class file name TestJunit3.java in C:\ > JUNIT_WORKSPACE
    import org.junit.Test;
    import junit.framework.AssertionFailedError;
    import junit.framework.TestResult;
    
    public class TestJunit3 extends TestResult {
       // add the error
       public synchronized void addError(Test test, Throwable t) {
          super.addError((junit.framework.Test) test, t);
       }
    
       // add the failure
       public synchronized void addFailure(Test test, AssertionFailedError t) {
          super.addFailure((junit.framework.Test) test, t);
       }
       @Test
       public void testAdd() {
       // add any test
       }
       
       // Marks that the test run should stop.
       public synchronized void stop() {
       //stop the test here
       }
    }
    Next, let's create a java class file name TestRunner3.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner3 {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestJunit3.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    }   
    Compile the Test case and Test Runner classes using javac
    C:\JUNIT_WORKSPACE>javac TestJunit3.java TestRunner3.java
    
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner3
    
    Verify the output.
    true
    

    TestSuite Class

    Following is the declaration for org.junit.TestSuite class:
    public class TestSuite extends Object implements Test
    A TestSuite is a Composite of Tests. It runs a collection of test cases. Some of the important methods of TestSuite class are
    S.N.Methods & Description
    1void addTest(Test test) Adds a test to the suite.
    2void addTestSuite(Class<? extends TestCase> testClass) Adds the tests from the given class to the suite.
    3int countTestCases() Counts the number of test cases that will be run by this test.
    4String getName() Returns the name of the suite.
    5void run(TestResult result) Runs the tests and collects their result in a TestResult.
    6void setName(String name) Sets the name of the suite.
    7Test testAt(int index) Returns the test at the given index.
    8int testCount() Returns the number of tests in this suite.
    9static Test warning(String message) Returns a test which will fail and log a warning message.
    Create a java class file name JunitTestSuite.java in C:\ > JUNIT_WORKSPACE to create Test suite
    import junit.framework.*;
    public class JunitTestSuite {
       public static void main(String[] a) {
          // add the test's in the suite
          TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class );
          TestResult result = new TestResult();
          suite.run(result);
          System.out.println("Number of test cases = " + result.runCount());
        }
    }
    Compile the Test suite classes using javac
    C:\JUNIT_WORKSPACE>javac JunitTestSuite.java 
    
    Now run the Test Suite.
    C:\JUNIT_WORKSPACE>java JunitTestSuite
    
    Verify the output.
    No of Test Case = 1
    Test Case Name = testAdd
    Updated Test Case Name = testNewAdd
    Number of test cases = 3
    
    
    
    
    
    
    
    
    Here we will see one complete example of JUnit testing using POJO class, Business logic class and a test class which will be run by test runner.
    Create EmployeeDetails.java in C:\ > JUNIT_WORKSPACE which is a POJO class.
    public class EmployeeDetails {
    
       private String name;
       private double monthlySalary;
       private int age;
       
       /**
       * @return the name
       */
       public String getName() {
          return name;
       }
       /**
       * @param name the name to set
       */
       public void setName(String name) {
          this.name = name;
       }
       /**
       * @return the monthlySalary
       */
       public double getMonthlySalary() {
          return monthlySalary;
       }
       /**
       * @param monthlySalary the monthlySalary to set
       */
       public void setMonthlySalary(double monthlySalary) {
          this.monthlySalary = monthlySalary;
       }
       /**
       * @return the age
       */
       public int getAge() {
          return age;
       }
       /**
       * @param age the age to set
       */
       public void setAge(int age) {
       this.age = age;
       }
    }
    EmployeeDetails class is used to
    • get/set the value of employee's name.
    • get/set the value of employee's monthly salary.
    • get/set the value of employee's age.
    Create a EmpBusinessLogic.java in C:\ > JUNIT_WORKSPACE which contains business logic
    public class EmpBusinessLogic {
       // Calculate the yearly salary of employee
       public double calculateYearlySalary(EmployeeDetails employeeDetails){
          double yearlySalary=0;
          yearlySalary = employeeDetails.getMonthlySalary() * 12;
          return yearlySalary;
       }
     
       // Calculate the appraisal amount of employee
       public double calculateAppraisal(EmployeeDetails employeeDetails){
          double appraisal=0;
          if(employeeDetails.getMonthlySalary() < 10000){
             appraisal = 500;
          }else{
             appraisal = 1000;
          }
          return appraisal;
       }
    }
    EmpBusinessLogic class is used for calculating
    • the yearly salary of employee.
    • the appraisal amount of employee.
    Create a TestEmployeeDetails.java in C:\ > JUNIT_WORKSPACE which contains test cases to be tested
    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    
    public class TestEmployeeDetails {
       EmpBusinessLogic empBusinessLogic =new EmpBusinessLogic();
       EmployeeDetails employee = new EmployeeDetails();
    
       //test to check appraisal
       @Test
       public void testCalculateAppriasal() {
          employee.setName("Rajeev");
          employee.setAge(25);
          employee.setMonthlySalary(8000);
          double appraisal= empBusinessLogic.calculateAppraisal(employee);
          assertEquals(500, appraisal, 0.0);
       }
    
       // test to check yearly salary
       @Test
       public void testCalculateYearlySalary() {
          employee.setName("Rajeev");
          employee.setAge(25);
          employee.setMonthlySalary(8000);
          double salary= empBusinessLogic.calculateYearlySalary(employee);
          assertEquals(96000, salary, 0.0);
       }
    }
    TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It
    • tests the yearly salary of the employee.
    • tests the appraisal amount of the employee.
    Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class TestRunner {
       public static void main(String[] args) {
          Result result = JUnitCore.runClasses(TestEmployeeDetails.class);
          for (Failure failure : result.getFailures()) {
             System.out.println(failure.toString());
          }
          System.out.println(result.wasSuccessful());
       }
    } 
    Compile the Test case and Test Runner classes using javac
    C:\JUNIT_WORKSPACE>javac EmployeeDetails.java 
    EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java
    
    Now run the Test Runner which will run test case defined in provided Test Case class.
    C:\JUNIT_WORKSPACE>java TestRunner
    
    Verify the output.
    true
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...