Assertions in TestCase

Assertions in TestCase


Posted in : Java Posted on : November 24, 2010 at 6:56 PM Comments : [ 0 ]

This section contains the detail about Assertions in TestCase

Assertions in TestCase

The core of the JUnit is the assertion.  Assertion is a Boolean expression which indicate an error if it returns false. The Assert class is the super class of all the JUnit test cases or classes. For using assertion in your Test case, you need to import Assert class.

A set of assertion methods useful for writing tests. Only failed assertions are recorded. Assertion are implemented with the intention of desired result , if we don't get the desired result, the outcome of the result  will be false.

Given below assertions and their description :

Assertion

Description

assertArrayEquals
(expeced array,actual array)

Asserts that two arrays are equal.

assertArrayEquals(String message,expected array,actual array)

Asserts that two byte arrays are equal. If they are not, an AssertionError is thrown with the given message.

assertsEquals(expected, actual)

Test if the values are the same.

assertFalse(String message, boolean condition)

Asserts that a condition is false.

assertNotNull(String message, Object object)

Asserts that an object isn't null.

assertNotSame(String message, Object unexpected, Object actual)

Asserts that two objects do not refer to the same object. continue......

assertSame(String message, Object expected, Object actual) Asserts that two objects refer to the same object.
assertTrue(boolean condition) Asserts that a condition is true.
fail(String message) Fails a test with the given message.
assertNull(String message, Object object) Asserts that an object is null.

Example :

Counter.java

package devmanuals.junit;

public class Counter {
int count=1;

public int increment(){
return ++count; 
}
public int decrement(){
return --count;
}
public int getcount(){
return count;
}
}

CounterTest.java(Test class)

package devmanuals.junit;

import static org.junit.Assert.*;

import org.junit.Test;
import devmanuals.junit.Counter;

public class CounterTest {
Counter ct = new Counter();

protected void setUp() { // create a (simple)Text fixture
ct = new Counter();
}

public void tearDown() {
}// No resources to releases

@Test
public void testIncrement() {
assertTrue(ct.increment() == 2);
}

@Test
public void testDecrement() {
assertTrue(ct.decrement() == 0);
}

@Test
public void testGetcount() {
assertEquals(1, ct.getcount());
}
}

Output

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics