assert java test code example
Example 1: java junit test
import org.junit.Assert;
import org.junit.Test;
public class Test {
public static int square(int n) {
return n * n;
}
@Test
public void squareTest() {
Assert.assertEquals(25, square(5));
Assert.assertEquals(16, square(4));
Assert.assertEquals(9, square(3));
Assert.assertEquals(4, square(2));
Assert.assertEquals(1, square(1));
}
}
Example 2: 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);
Example 3: assert java
public void setup() { Connection conn = getConnection(); assert conn != null;}