Album Cover

Microtesting Java

Close Preview
In every assert you indicate the value you expect.
JUnit will compare it to the actual value from the code under test.
The code in the tabs below shows how to assert information about various types.
Check that two Objects are equal:

public void stringEquality() {
	String expected = "Something";
	String actual   = "Something";
	assertEquals(expected, actual);
Know that: This assert invokes the objects' equals method (defined on them, or inherited from Object, as the case may be).
Check that two integers are equal:

public void intEquality() {
	int expected = 10;
	int actual   = 10;
	assertEquals(expected, actual);
@Test public void integerEquality() { Integer expected = new Integer(11); Integer actual = new Integer(11); assertEquals(expected, actual); }
Due to their internal representation, it is tricky to say when two floats or two doubles are equal. The canonical solution is to assert equality to within a certain precision, or tolerance:

public void doubleEquality() {
	double expected  = 10.01;
	double actual    = 10.01;
	double precision = 0.000001;
	assertEquals(expected, actual, precision);
@Test public void floatEquality() { float expected = 10.0001F; float actual = 10.00009F; float precision = 0.0001F; assertEquals(expected, actual, precision); }
Check that Object references (like Integer or String) point to the same object, or whether they are null or not.

public void objectsSame() {
	Integer anObject = new Integer(1);
	Integer sameObject = anObject;
	assertSame(anObject, sameObject);
@Test public void objectsNotSame() { Integer anObject = new Integer(1); Integer anotherObject = new Integer(1); assertNotSame(anObject, anotherObject); }
@Test public void nullObject() { String object = null; assertNull(object); }
@Test public void nonNullObject() { String object = "hello"; assertNotNull(object); }
Check that a boolean expression is true or false:

public void booleanTrue() {
	boolean result = true;
@Test public void booleanFalse() { boolean result = false; assertFalse(result); }
Assert methods live in org.junit.Assert, so you need to import static org.junit.Assert.*, or import static org.junit.Assert.<the specific assert you need>.
| Tweet...
Page rating: | Rate this Page