Junit

Unit Test Case
  • It is a part of code which ensures that other part of code works as expected.
  • A unit test case is characterized by a known input called as precondition and an expected output called as post condition
  • There must be at least two unit test cases for each requirement - one positive test and one negative test.
  • Testing promotes Code reliability, robustness and ensures high-quality software is delivered.
  • Code is declared as unstable if it fails any of test cases.
  • REST Api’s must pass through unit testing as well as integration testing.
  • Software test is a piece of code that executes another piece of code asserting that it is behaving in a way we want to.
  • The test cases are executed by the build system.
  • Running test cases automatically helps to check software regressions.
  • Having high test coverage allows us to perform lot of tests without manual tests
  • It is safe to ignore trivial code.
  • Testing terminology
    • Test fixture all fixed state of baseline objects for running tests.
    • Code Under test is the code being tested.
    • Application under test is the application being tested.
    • Unit test is a test case written by developer to check behaviour of Code.
      • Unit test targets, a small part of Code, such as a method or a class.
      • This is done by mocking that part of Code.
    • Integration test checks for integration between components.
    • A behaviour test checks for correctness of input parameter of a method.
    • Percentage of code checked by unit test is called as code coverage.
JUnit
  • JUnit is a unit testing framework for java programming language.
  • Promotes the idea of "first testing then coding",
  • Opensource framework which is used for writing and running tests.
  • Provides annotations to identify test methods
  • Provides assertions for testing expected results.
  • Provides test runner for running tests.
  • Junit tests allow you to write codes faster,which increases quality.
  • Tests can be run automatically and they check their own results and provide immediate feedback.
  • Tests can be organized into test suites containing test cases and even other test suites.
  • The most important package in Junit is junit.framework which contains all the core classes.
  • The testcases are executed using JUnitCore class.
  • JUnitCore is a facade for running tests.
  • To run tests from command line use
    • Java org.junit.runner.JUnitCore <Test Class>
Features of JUnit
  • 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 has following methods
      • setUp() Method
        • runs before test invocation.
      • tearDown() Method
        • runs after every test method.
 package javaimplant.junitTest;  
 import junit.framework.TestCase;  
 public class Fixtures 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 Suites
    • A test suit bundles a few unit test cases and runs them together.
    • @RunWith and @Suit annotation are used to run the suit test.
    MessageUtil
     package javaimplant.junitTest;  
     public class MessageUtil {  
          String msg;  
          public MessageUtil(String message) {  
               this.msg=message;  
          }  
          public String printMessage() {  
               // TODO Auto-generated method stub  
               return msg;  
          }  
          public String salutationMessage() {  
               // TODO Auto-generated method stub  
               return "Hi!" + msg;  
          }  
     }  
    
    TestJUnit1
     package javaimplant.junitTest;  
     import static org.junit.Assert.assertEquals;  
     import org.junit.Test;  
     public class TestJunit1 {  
          String message = "Robert";       
          MessageUtil messageUtil = new MessageUtil(message);  
          @Test  
          public void testPrintMessage() {       
        System.out.println("Inside testPrintMessage()");    
        assertEquals(message, messageUtil.printMessage());     
          }  
     }  
    
    TestJUnit2
     package javaimplant.junitTest;  
     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());  
            }  
     }  
    
    JunitTestSuite
     package javaimplant.junitTest;  
     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 {  
     }  
    
      Test Runners
      • Test Runner is used for executing test cases.
       package javaimplant.junitTest;  
       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, used in writing and testing Junit
        • Some of the important classes are
          • Assert
            • Contains set of Assert methods
            • Methods of Assert Class
              • void assertEquals(boolean expected, boolean actual)
                • Checks that two primitives/objects are equal.
              • void assertFalse(boolean condition)
                • Checks that a condition is false.
              • void assertNotNull(Object object)
                • Checks that an object isn't null.
              • void assertNull(Object object)
                • Checks that an object is null.
              • void assertTrue(boolean condition)
                • Checks that a condition is true.
              • void fail()
                • Fails a test with no message
          • TestCase
            • Contains a Test Case that defines the fixture to run multiple tests.
            • Methods of TestCase Class
              • int countTestCases()
                • Counts the number of test cases executed by run(TestResult result).
              • TestResult createResult()
                • Creates a default TestResult object.
              • String getName()
                • Gets the name of a TestCase.
              • TestResult run()
                • A convenience method to run this test, collecting the results with a default TestResult object.
              • void run(TestResult result)
                • Runs the test case and collects the results in TestResult.
              • void setName(String name)
                • Sets the name of a TestCase.
              • void setUp()
                • Sets up the fixture, for example, open a network connection.
              • void tearDown()
                • Tears down the fixture, for example, close a network connection.
              • String toString()
                • Returns a string representation of the test case.
          • TestResult
            • Contains methods to collect the results of executing a test case.
            • Collects the results of executing a test case.
            • Methods of TestCase Class
              • void addError(Test test, Throwable t)
                • Adds an error to the list of errors.
              • void addFailure(Test test, AssertionFailedError t)
                • Adds a failure to the list of failures.
              • void endTest(Test test)
                • Informs the result that a test was completed.
              • int errorCount()
                • Gets the number of detected errors.
              • Enumeration<TestFailure> errors()
                • Returns an Enumeration for the errors.
              • int failureCount()
                • Gets the number of detected failures.
              • void run(TestCase test)
                • Runs a TestCase.
              • int runCount()
                • Gets the number of run tests.
              • void startTest(Test test)
                • Informs the result that a test will be started.
              • void stop()
                • Marks that the test run should stop.
          • Test Suit
            • A test Suit is a composite of tests.
            • Methods of TestSuit Class are as follows
              • void addTest(Test test)
                • Adds a test to the suite.
              • void addTestSuite(Class<? extends TestCase> testClass)
                • Adds the tests from the given class to the suite.
              • int countTestCases()
                • Counts the number of test cases that will be run by this test.
              • String getName()
                • Returns the name of the suite.
              • void run(TestResult result)
                • Runs the tests and collects their result in a TestResult.
              • void setName(String name)
                • Sets the name of the suite.
              • Test testAt(int index)
                • Returns the test at the given index.
              • int testCount()
                • Returns the number of tests in this suite.
              • static Test warning(String message)
                • Returns a test which will fail and log a warning message.
         package javaimplant.junitTest;  
         import org.junit.Test;  
         import junit.framework.TestCase;  
         import org.junit.Ignore;  
         import static org.junit.Assert.assertEquals;  
         import org.junit.Before;  
         public class TestJunit2 extends TestCase {  
              protected double fValue1;  
              protected double fValue2;  
              String message = "Robert";       
              MessageUtil messageUtil = new MessageUtil(message);  
              @Before  
              protected void setUp() throws Exception {  
                    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( )   
           {  
           }  
           @Test  
           public void testSalutationMessage() {  
            System.out.println("Inside testSalutationMessage()");  
            message = "Hi!" + "Robert";  
            assertEquals(message,messageUtil.salutationMessage());  
           }  
         }  
        
          Annotations
          • These are like meta-tags that you can add to your code,and apply them to in our Test Class
          • Annotations provide following information about test methods.
            • Which methods are going to run before and after Test Methods
            • Which methods run before and after all methods.
            • Which methods or classes will be ignored during the Execution
          • Following are the annotations available in Junit
            • @Test
              • The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
            • @Before
              • Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method.
            • @After
              • If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method.
            • @BeforeClass
              • Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class.
            • @AfterClass
              • This will perform the method after all tests have finished. This can be used to perform clean-up activities.
            • @Ignore
              • The Ignore annotation is used to ignore the test and that test will not be executed.
                • A test method annotated with @Ignore will not be executed.
                • A test class annotated with @Ignore then none of its test methods will be executed.
          Timeout
              • JUnit provides an option for timeout
                • If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed.
                • The timeout parameter is used along with @Test annotation.
                • In JUnit5 we test using assertTimeout method.
              Exceptions Test
              • Junit provides an option of tracing the exception handling of code.
              • We can test whether the code throws an exception or not
                • The excepted parameter is used along with @Test annotation.
                • In Junit5 we test using Assertions.assertThrows(Exception.class,()->{method});
              Parameterized Test
              • Parameterized tests allow a developer to run a same test case over and over again using different values.
                • Annotate Test Class with @RunWith(Paramaterized.class)
                • Create a public static method annotated with @Parameters that returns a collection of objects(as Array) or Test Data Set.
                • Create a public constructor that takes in what is equivalent to one "row " of test data.
                • Create an instance variable for each "column" of Test Data.
                • Create your test cases using the instance variables as the source of the Test Data.
              • The testCase will be invoked once for each row of data.
              Junit with ANT
               <project name = "JunitTest" default = "test" basedir = ".">  
                 <property name = "testdir" location = "../test" />  
                 <property name = "srcdir" location = "../src/javaimplant/junitTest" />  
                 <property name = "full-compile" value = "true" />  
                 <path id = "classpath.base"/>  
                 <path id = "classpath.test">  
                  <pathelement location = "../lib/junit-4.13.jar" />  
                  <pathelement location = "../lib/junit-jupiter-api-5.6.0.jar" />  
                  <pathelement location = "${testdir}" />  
                  <pathelement location = "${srcdir}" />  
                  <path refid = "classpath.base" />  
                 </path>  
                 <target name = "clean" >  
                  <delete verbose = "${full-compile}">  
                    <fileset dir = "${testdir}" includes = "**/*.class" />  
                  </delete>  
                 </target>  
                 <target name = "compile" depends = "clean">  
                  <javac srcdir = "${srcdir}" destdir = "${testdir}" verbose = "${full-compile}">  
                    <classpath refid = "classpath.test"/>  
                  </javac>  
                 </target>  
                 <target name = "test" depends = "compile">  
                  <junit>  
                    <classpath refid = "classpath.test" />  
                    <formatter type = "brief" usefile = "false" />  
                    <test name = "TestMessageUtil" />  
                  </junit>  
                 </target>  
               </project>  

              dd

              No comments:

              Post a Comment