JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
The Assert class provides static methods for verifying expected behavior in tests. When an assertion fails, it throws an AssertionError causing the test to fail. All assertion methods are available with and without an optional message parameter that describes the assertion.
Verify that two values are equal using the equals() method. Supports all object types and primitives with specialized overloads for better failure messages.
/**
* Asserts that two objects are equal
* @param message - Optional message to display on failure
* @param expected - Expected value
* @param actual - Actual value
*/
public static void assertEquals(String message, Object expected, Object actual);
public static void assertEquals(Object expected, Object actual);
// Primitive overloads for better error messages
public static void assertEquals(String message, long expected, long actual);
public static void assertEquals(long expected, long actual);
public static void assertEquals(String message, double expected, double actual, double delta);
public static void assertEquals(double expected, double actual, double delta);
public static void assertEquals(String message, float expected, float actual, float delta);
public static void assertEquals(float expected, float actual, float delta);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class EqualityTest {
@Test
public void testBasicEquality() {
assertEquals(4, 2 + 2);
assertEquals("hello", "hel" + "lo");
assertEquals(100L, 100L);
}
@Test
public void testWithMessage() {
assertEquals("Addition should work", 10, 5 + 5);
}
@Test
public void testFloatingPoint() {
// For floating point, provide delta for precision
assertEquals(0.33, 1.0 / 3.0, 0.01);
assertEquals("Pi approximation", 3.14, Math.PI, 0.01);
}
@Test
public void testObjects() {
Person expected = new Person("Alice", 30);
Person actual = new Person("Alice", 30);
assertEquals(expected, actual); // Uses Person.equals()
}
}Verify that two values are not equal. Added in JUnit 4.11 to complement assertEquals.
/**
* Asserts that two objects are not equal
* @param message - Optional message to display on failure
* @param unexpected - Value that should not match
* @param actual - Actual value
*/
public static void assertNotEquals(String message, Object unexpected, Object actual);
public static void assertNotEquals(Object unexpected, Object actual);
// Primitive overloads
public static void assertNotEquals(String message, long unexpected, long actual);
public static void assertNotEquals(long unexpected, long actual);
public static void assertNotEquals(String message, double unexpected, double actual, double delta);
public static void assertNotEquals(double unexpected, double actual, double delta);
public static void assertNotEquals(String message, float unexpected, float actual, float delta);
public static void assertNotEquals(float unexpected, float actual, float delta);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class InequalityTest {
@Test
public void testNotEqual() {
assertNotEquals(5, 2 + 2);
assertNotEquals("Different strings", "hello", "world");
}
@Test
public void testFloatingPointNotEqual() {
assertNotEquals(0.5, 1.0 / 3.0, 0.01);
}
}Verify boolean conditions. The most commonly used assertions in unit testing.
/**
* Asserts that a condition is true
* @param message - Optional message to display on failure
* @param condition - Condition to check
*/
public static void assertTrue(String message, boolean condition);
public static void assertTrue(boolean condition);
/**
* Asserts that a condition is false
* @param message - Optional message to display on failure
* @param condition - Condition to check
*/
public static void assertFalse(String message, boolean condition);
public static void assertFalse(boolean condition);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class BooleanTest {
@Test
public void testConditions() {
assertTrue(5 > 3);
assertFalse(5 < 3);
assertTrue("List should not be empty", !list.isEmpty());
}
@Test
public void testComplexConditions() {
List<String> items = getItems();
assertTrue("List should contain at least 5 items", items.size() >= 5);
assertFalse("List should not be empty", items.isEmpty());
}
}Check for null and non-null values.
/**
* Asserts that an object is null
* @param message - Optional message to display on failure
* @param object - Object to check
*/
public static void assertNull(String message, Object object);
public static void assertNull(Object object);
/**
* Asserts that an object is not null
* @param message - Optional message to display on failure
* @param object - Object to check
*/
public static void assertNotNull(String message, Object object);
public static void assertNotNull(Object object);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class NullTest {
@Test
public void testNullChecks() {
String nullString = null;
assertNull(nullString);
String nonNullString = "hello";
assertNotNull(nonNullString);
assertNotNull("Result should not be null", database.query());
}
@Test
public void testOptionalValue() {
Optional<String> result = findUser("unknown");
assertNotNull("Optional should not be null", result);
assertFalse("Optional should be empty", result.isPresent());
}
}Verify that two references point to the same object (using == instead of equals()).
/**
* Asserts that two references point to the same object
* @param message - Optional message to display on failure
* @param expected - Expected reference
* @param actual - Actual reference
*/
public static void assertSame(String message, Object expected, Object actual);
public static void assertSame(Object expected, Object actual);
/**
* Asserts that two references point to different objects
* @param message - Optional message to display on failure
* @param unexpected - Reference that should not match
* @param actual - Actual reference
*/
public static void assertNotSame(String message, Object unexpected, Object actual);
public static void assertNotSame(Object unexpected, Object actual);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class ReferenceTest {
@Test
public void testSameReference() {
String str1 = "hello";
String str2 = str1;
assertSame("Should be same reference", str1, str2);
String str3 = new String("hello");
assertNotSame("Should be different references", str1, str3);
assertEquals("But should be equal", str1, str3);
}
@Test
public void testSingleton() {
Database db1 = Database.getInstance();
Database db2 = Database.getInstance();
assertSame("Singleton should return same instance", db1, db2);
}
}Compare arrays element by element. Provides better error messages than comparing arrays with assertEquals.
/**
* Asserts that two arrays are equal (same length and equal elements)
* @param message - Optional message to display on failure
* @param expecteds - Expected array
* @param actuals - Actual array
*/
public static void assertArrayEquals(String message, Object[] expecteds, Object[] actuals);
public static void assertArrayEquals(Object[] expecteds, Object[] actuals);
// Primitive array overloads
public static void assertArrayEquals(String message, boolean[] expecteds, boolean[] actuals);
public static void assertArrayEquals(boolean[] expecteds, boolean[] actuals);
public static void assertArrayEquals(String message, byte[] expecteds, byte[] actuals);
public static void assertArrayEquals(byte[] expecteds, byte[] actuals);
public static void assertArrayEquals(String message, char[] expecteds, char[] actuals);
public static void assertArrayEquals(char[] expecteds, char[] actuals);
public static void assertArrayEquals(String message, short[] expecteds, short[] actuals);
public static void assertArrayEquals(short[] expecteds, short[] actuals);
public static void assertArrayEquals(String message, int[] expecteds, int[] actuals);
public static void assertArrayEquals(int[] expecteds, int[] actuals);
public static void assertArrayEquals(String message, long[] expecteds, long[] actuals);
public static void assertArrayEquals(long[] expecteds, long[] actuals);
public static void assertArrayEquals(String message, double[] expecteds, double[] actuals, double delta);
public static void assertArrayEquals(double[] expecteds, double[] actuals, double delta);
public static void assertArrayEquals(String message, float[] expecteds, float[] actuals, float delta);
public static void assertArrayEquals(float[] expecteds, float[] actuals, float delta);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class ArrayTest {
@Test
public void testIntArray() {
int[] expected = {1, 2, 3, 4, 5};
int[] actual = generateSequence(5);
assertArrayEquals(expected, actual);
}
@Test
public void testStringArray() {
String[] expected = {"apple", "banana", "cherry"};
String[] actual = getFruits();
assertArrayEquals("Fruit list should match", expected, actual);
}
@Test
public void testDoubleArray() {
double[] expected = {1.1, 2.2, 3.3};
double[] actual = getValues();
assertArrayEquals(expected, actual, 0.01);
}
@Test
public void testByteArray() {
byte[] expected = {0x01, 0x02, 0x03};
byte[] actual = getData();
assertArrayEquals(expected, actual);
}
}Assert that code throws a specific exception type. Added in JUnit 4.13, provides better syntax than @Test(expected=...).
/**
* Asserts that the given runnable throws an exception of the expected type
* Returns the thrown exception for further assertions
* @param expectedThrowable - Expected exception class
* @param runnable - Code to execute
* @return The thrown exception
*/
public static <T extends Throwable> T assertThrows(
Class<T> expectedThrowable,
ThrowingRunnable runnable
);
/**
* Asserts that the given runnable throws an exception of the expected type
* @param message - Message to display on failure
* @param expectedThrowable - Expected exception class
* @param runnable - Code to execute
* @return The thrown exception
*/
public static <T extends Throwable> T assertThrows(
String message,
Class<T> expectedThrowable,
ThrowingRunnable runnable
);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class ExceptionTest {
@Test
public void testException() {
assertThrows(IllegalArgumentException.class, () -> {
divide(10, 0);
});
}
@Test
public void testExceptionWithMessage() {
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> new User(-1, "Invalid")
);
assertEquals("Age must be positive", ex.getMessage());
}
@Test
public void testExceptionWithCustomMessage() {
assertThrows(
"Should throw exception for invalid input",
NullPointerException.class,
() -> processNull(null)
);
}
}Assert using Hamcrest matchers for expressive, readable assertions. Requires Hamcrest library on classpath.
Note: These methods are deprecated as of JUnit 4.13. Use org.hamcrest.MatcherAssert.assertThat() instead.
/**
* Asserts that actual value matches the given Hamcrest matcher
* @param actual - Actual value
* @param matcher - Hamcrest matcher
* @deprecated use {@code org.hamcrest.MatcherAssert.assertThat()}
*/
@Deprecated
public static <T> void assertThat(T actual, Matcher<? super T> matcher);
/**
* Asserts that actual value matches the given Hamcrest matcher
* @param reason - Message to display on failure
* @param actual - Actual value
* @param matcher - Hamcrest matcher
* @deprecated use {@code org.hamcrest.MatcherAssert.assertThat()}
*/
@Deprecated
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher);Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class MatcherTest {
@Test
public void testWithMatchers() {
assertThat(5, is(5));
assertThat("hello", startsWith("hel"));
assertThat("world", containsString("orl"));
assertThat(10, not(equalTo(5)));
}
@Test
public void testCollections() {
List<String> items = Arrays.asList("apple", "banana", "cherry");
assertThat(items, hasItem("banana"));
assertThat(items, hasItems("apple", "cherry"));
assertThat(items.size(), is(3));
}
@Test
public void testWithReason() {
assertThat("Age should be valid", age, greaterThan(0));
assertThat("Name should not be empty", name, not(isEmptyString()));
}
}Explicitly fail a test with an optional message. Useful for marking unreachable code or creating custom validation logic.
/**
* Fails a test with the given message
* @param message - Message explaining the failure
*/
public static void fail(String message);
/**
* Fails a test with no message
*/
public static void fail();Usage Examples:
import org.junit.Test;
import static org.junit.Assert.*;
public class FailTest {
@Test
public void testShouldNotReachHere() {
try {
methodThatShouldThrow();
fail("Expected exception was not thrown");
} catch (ExpectedException e) {
// Expected
}
}
@Test
public void testConditionalFail() {
Result result = performOperation();
if (result.hasErrors()) {
fail("Operation failed: " + result.getErrorMessage());
}
}
@Test
public void testUnimplemented() {
if (!isFeatureImplemented()) {
fail("Feature not yet implemented");
}
testFeature();
}
}/**
* Functional interface for code that may throw exceptions
* Used with assertThrows
*/
@FunctionalInterface
public interface ThrowingRunnable {
void run() throws Throwable;
}
/**
* Thrown when an assert equals specifically for Strings fails
* Provides formatted output showing differences between expected and actual
*/
public class ComparisonFailure extends AssertionError {
public ComparisonFailure(String message, String expected, String actual);
public String getExpected();
public String getActual();
public String getMessage();
}
/**
* Thrown when an assertion fails
*/
public class AssertionError extends Error {
public AssertionError();
public AssertionError(String message);
public AssertionError(String message, Throwable cause);
}Install with Tessl CLI
npx tessl i tessl/maven-junit--junit