JUnit 4.x – Testing Framework : Error Example
Error Example |
Item.java
package com.javaskool;
public class Item
{
private int[] array;
public Item(int size) {
array= new int[size];
}
public String getHelloWorld() {
return "Hello World";
}
public boolean getTruth() {
return true;
}
public void setElement(int position, int value) throws ArrayIndexOutOfBoundsException {
array[position] = value;
}
public int getElement(int position) throws ArrayIndexOutOfBoundsException {
return array[position];
}
}
ItemTest.java
package com.javaskool;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ItemTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
Item i=new Item(3); //3 elements only so last index 2
String s=i.getHelloWorld();
assertEquals("wrong Message", "Hello World", s);
boolean t=i.getTruth();
assertEquals(true,t);
i.setElement(0, 10);
i.setElement(1, 20);
i.setElement(2, 30);
i.setElement(3, 30);// this will generate Errors
}
}
Exception Example |
JUnit provides a option of tracing the Exception handling of code.
You can test the code whether code throws desired exception or not.
The expected parameter is used along with @Test annotation. Now let’s see @Test(expected) in action.
MessageUtil.java
package com.javaskool;
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public void printMessage(){
System.out.println(message);
int a = 0;
int b = 1/a;
}
// add "Hi!" to the message
public String salutationMessage(){
message = "Hi!" + message;
System.out.println(message);
return message;
}
}
MyExceptionTest.java
package com.javaskool;
import static org.junit.Assert.*;
import org.junit.Test;
public class MyExceptionTest {
String message = "James";
MessageUtil messageUtil = new MessageUtil(message);
@Test(expected = ArithmeticException.class)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "James";
assertEquals(message,messageUtil.salutationMessage());
}
}
Downloads Examples |
Click here to Download Error JUnit Test Example
Click here to Download Exception JUnit Test Example
Click here to Download Annotation based JUnit Example
Click here to Download Shopping Cart JUnit Example
Recent Comments