Tuesday, November 24, 2015

JUnit 4 Annotations

JUnit 4

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

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


Program1.java


package com.javaetutorials;

public class Program1 {

String truncateTwoPositions(String str) {
if (str.length() <= 2)
return str.replaceAll("A", "");
String firstTwoChars = str.substring(0, 2);
String StringMinusFirstTwoChars = str.substring(2);
return firstTwoChars.replaceAll("A", "") + StringMinusFirstTwoChars;
}

Boolean firstAndLastTwoChars(String str) {
if (str.length() <= 1)
return false;
if (str.length() <= 2)
return true;
String str1=str.substring(0, 2);
String str2=str.substring(str.length()-2);
return str1.equals(str2);
}
}

Program1Test.java

package com.javaetutorials;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class Program1Test {

Program1 p;

@BeforeClass // must be static...run only once...
public static void beforeClass(){
System.out.println("BeforeClass");
}

@AfterClass
public static void afterClass(){
System.out.println("AfterClass");
}

@Before // Before runs before every Test
public void before(){
p=new Program1();
System.out.println("Before Method");
}

@After // After runs after Every Test
public void after(){
p=null;
System.out.println("After Method");
}

@Test
public void TestProgram1() {
System.out.println("TestProgram1");
assertEquals("BCC", p.truncateTwoPositions("ABCC"));
assertEquals("BBAA", p.truncateTwoPositions("BBAA"));
assertEquals("BB", p.truncateTwoPositions("AABB"));
}

@Test
public void TestfirstAndLastTwoChars(){
System.out.println("TestfirstAndLastTwoChars");
assertTrue(p.firstAndLastTwoChars("AA"));
assertTrue(p.firstAndLastTwoChars("ABAB"));
assertFalse(p.firstAndLastTwoChars("ABABC"));
}

//Exception based Annotations...
@Test(expected=NullPointerException.class)
public void TestArrays(){
int[] num={5,4,3,2,1};
Arrays.sort(num);
int[] expOut={1,2,3,4,5};
assertArrayEquals(num,expOut);
int[] num1=null;
Arrays.sort(num1);
assertArrayEquals(num1,expOut);
}

//Performance Testing...
@Test(timeout=10)
public void TestPerformance(){
System.out.println("Hey Performance");
}

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

Output :

BeforeClass
Before Method
After Method
Before Method
TestfirstAndLastTwoChars
After Method
Before Method
TestProgram1
After Method
Before Method
Hey Performance
After Method
AfterClass


No comments:

Post a Comment