All About xUnit
Assertions
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.JUnit will compare it to the actual value from the code under test.
Check that two
Object
s are equal:
@Test
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:
@Test
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
float
s or two double
s are equal.
The canonical solution is to assert equality to within a certain precision, or tolerance:
@Test
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.
@Test
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:
@Test
public void booleanTrue() {
boolean result = true;
assertTrue(result);
}@Test
public void booleanFalse() {
boolean result = false;
assertFalse(result);
}
org.junit.jupiter.api.Assertions
, so you
need to:
import static org.junit.jupiter.api.Assertions.*
, orimport org.junit.jupiter.api.Assertions.
<the specific assert you need>.
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |