Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 22 July 2013

Junit Concept | Junit tutorial with example code

JUnit4 Annotations are single big change from JUnit 3 to JUnit 4 which is introduced in Java 5. With annotations in Junit4,  creating and running a JUnit test becomes more easy and more readable, but you can only take full advantage of JUnit4 if you know the correct meaning of  JUnit 4 annotations and how to use them while writing JUnit tests. In this
Junit tutorial we will not only understand meaning of those annotations but also we will see examples of JUnit4 annotations. By the way this is my first post in JUnit 4 but if you are new here than you may like post 10 tips to write better code comments and 10 Object oriented design principles for Programmer as well.

JUnit 4 Annotations : Overview
Following is a list of frequently used JUnit4 Annotation , which is available when you include junit4.jar in your Classpath:

@Before
@BeforeClass
@After
@AfterClass
@Test
@Ignore
@Test(timeout=500)
@Test(expected=IllegalArgumentException.class)


@Before and @After
In Junit4 there is no setup() or tearDown() method and instead of that we have @Before and @After annotations.
By using @Before you can make any method as setup() and by using @After you can make any method as teardown(). What is most important point to remember is @Before and @After annotated method will be invoked before and after each test case. So in case you have five test cases in your JUnit test file than just like setup() and tearDown() method annotated with @Before and @After will be called five times. Here is an example of using
@Before and @After Annotation in JUnit4:

    @Before
    public void setUp() {
        System.out.println("@Before method will execute before every JUnit4 test");
    }

    @After
    public void tearDown() {
        System.out.println("@After method will execute before every JUnit4 test");
    }


@BeforeClass and @AfterClass
@BeforeClass and @AfterClass JUnit4 Annotations are similar to @After and @Before with only exception that they
are called on per TestClass basis and not on per test basis. They can be used as one time setup and tearDown
method and can be used to initialize class level resources. here is an example of using @BeforeClass and @AfterClass Annotations in JUnit4, here is an example of @BeforeClass and @AfterClass Junit 4 annotation

    @BeforeClass
    public static void setUpClass() throws Exception {
        System.out.println("@BeforeClass method will be executed before JUnit test for"
                + "a Class starts");
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
         System.out.println("@AfterClass method will be executed after JUnit test for"
                + "a Class Completed");
    }


@Test
@Test is a replacement of both TestCase class and convention "test" which we prefix to every test method. for example to test a method  called calculateInterest() we used to create method testCalcuatedInterest() and our class needs to be extended from org.junit.TestCase class. Now with @Test annotation that is not required any more. You just need to annotate your test method with @Test Junit4 annotation and done. no need to extend from TestCase class and no need to prefix "test" to your method, here is an example of  JUnit 4 @Test annotation

 @Test
    public void testCalculateInterest() {
        System.out.println("calculateInterest");
        fail("An Example of @Test JUnit4 annotation");
    }


@Ignore
JUnit 4 Annotations examples list meaningsSome time we add test method in JUnit test class but hasn't implemented that is causing your build to fail if JUnit testcase are integrated or embedded into build process. you can avoid that problem by marking your test method as @Ignore in Junit4. JUnit4 ignores method annotated with @Ignore and doesn't run during test. Here is an example of using @Ignore annotation in JUnit4 to exclude a particular Test from running:


 @Ignore("Not yet implemented")
    @Test
    public void testGetAmount() {
        System.out.println("getAmount");
        fail("@Ignore method will not run by JUnit4");
    }


@Test(timeout=500)
Now with JUnit4 writing testcases based on timeout is extremely easy. You just need to pass a parameter timeout with value in millisecond to @Test annotation. remember timeout values are specified in millisecond and your JUnit4 timeout test case will help if it doesn't complete before timeout period. This works great if you have SLA(Service Level Agreement)  and an operation need to complete before predefined timeout.

  @Test(timeout = 500)
    public void testTimeout() {
        System.out.println("@Test(timeout) can be used to enforce timeout in JUnit4 test case");
        while (1 == 1) {
        
        }
    }

This JUnit4 test will fail after 500 millisecond.

@Test(expected=IllegalArgumentException.class)
Another useful enhancement is Exception handling testcases of JUnit4. Now to test Exception is become very easy and you just need to specify Exception class inside @Test annotation to check whether a method throws a particular exception or not. here is an example which test behavior of a method to verify whether it throws Exception or not,  when run with invalid input:

    @Test(expected=IllegalArgumentException.class)
    public void testException(int input) {
        System.out.println("@Test(expected) will check for specified exception during its run");
    
    }


These were list of frequently used JUnit 4 annotations and there meanings. In the course we have also learn how to use @Before , @After in place of setup() and teardown(). Code review and Unit testing is one of the best development practices to follow and we must try our best to incorporate that in our daily coding and development cycle.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...