Features of JUnit

  • JUnit is an open source framework, which is used for writing and running tests.
  • Provides annotations to identify test methods.
  • Provides assertions for testing expected results.
  • Provides test runners for running tests.
  • JUnit tests allow you to write codes faster, which increases quality.
  • JUnit is elegantly simple. It is less complex and 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 the test is running smoothly, 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 another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language.
A formal written unit test case is characterized by a known input and 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.
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.

Test JUnit Setup

Create a java class file name TestJunit:-
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 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());
   }
}   

Verify the Result:

Verify the output.
true


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 following −
  • Eclipse
  • Ant
  • Maven


































No comments:

Post a Comment