Saturday, August 4, 2012

JUnit: Basic Annotations


What is JUnit?

JUnit 4.x is a test framework which uses annotations to identify methods that are test methods. JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.
To write a test with JUnit
  • Annotate a method with @org.junit.Test
  • Use a method provided by JUnit to check the expected result of the code execution versus the actual result
You can use Eclipse or the org.junit.runner.JUnitCore class to run the test.

Various Annotations of JUnit:


  1. @Test: This annotations tells which method is a test method. 

    @Test
    public void methondName(){
    ...........
    }


    You can some parameters with this annotations.
    • @Test (expected = Exception.class) Fails, if the method does not throw the named exception. 
    • @Test(timeout=1000) Fails, if the method takes longer than 100 milliseconds.

  2. @Before: The method which this annotation will execute before each test method. For example in cases where you need to initialize new class or read input data.

    @Before
    public void methodName(){
    ........
    }
  3. @After: This annotation signifies the method which executes after each test. For example where you need to roll back changes done by tests. 

    @After
    public void methodName(){
    ........
    }
  4. @BeforeClass: Method with this annotations executes only once before the start of all tests. This can be used in case where you need a database connection for the tests and you create it only once in the beginning. 

    @BeforeClass
    public void methodName(){
    ........
  5. @AfterClass: This annotation signifies the method which executes only once and that too at the end of all tests for example to close the data connection. 

    @AfterClass
    public void methodName(){
    ........
    }
  6. @Ignore: Will ignore the test method. You can use it in cases where your code has changed and the test is not yet adapted to accommodate those changes. 

    @Ignore
    public void methodName(){
    ........
    }
     

No comments:

Follow by Email