java assert test code example
Example 1: java testing with assertions
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class AssertionExample {
/**
* The assertionExample function
* uses multiple assertions for the purpose of example;
* Usually in one method it is recommended to have 1 assertion;
*/
@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: 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));
}
}