assertequals junit code example
Example 1: java testing with assertions
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class AssertionExample {
@Test
public void assertionExample()
{
Assertions.assertEquals(2+2,4);
Assertions.assertNotEquals(6+3,10);
Assertions.assertTrue("Radu".length()==4);
String tester = null;
Assertions.assertThrows(NullPointerException.class,()->tester.equals("emptyString"));
}
}
Example 2: assert multiple junit
public void shouldTellIfPrime(){
Assertions.assertAll(
() -> assertTrue(isPrime(2)),
() -> assertFalse(isPrime(4))
);
}
Example 3: what is assertion in junit
soft assertion:
-There is no soft assert in junit.
Only testNG has it.
- Soft assert: won't stop the execution
if assertion fails.
- Soft assert methods are not static,
so we must create the object of the class.
- It displayS the recorded result at the end.
I use soft assertion when functionality is NOT
very critical.
hard assertion:
- Hard assert: will stop the execution
of the test when it fails.
- The line we have the hard assert, if fails,
rest of the lines will not be executed.
- Hard assertion methods are static,
therefore we are able to use them without
having to create the object of the class.
SYNTAX===
hard assertion:
Assert.assertEquals(ExpectedStr,ActualStr);
soft assertion:
SoftAssert softAssert = new SoftAssert();
softAssert.assertTrue(2<1);