Why start with AssertionError?
Starting something new can be exciting, but it can also be overwhelming!! It’s natural to want to dig deeper into every little detail, even if it seems small. Recently, while attempting to showcase a straightforward testing framework, I encountered an error message in the console.
![](https://static.wixstatic.com/media/nsplsh_6ac535bc9892424ba8c587fb66dfa4f6~mv2.jpg/v1/fill/w_147,h_98,al_c,q_80,usm_0.66_1.00_0.01,blur_2,enc_auto/nsplsh_6ac535bc9892424ba8c587fb66dfa4f6~mv2.jpg)
Currently, I am utilizing IntelliJ IDE for practice.
STEP 1: DEPENDENCY CONFIGURATION
At the outset, I established a Maven project and integrated the essential dependencies in the pom.xml file. Specifically, I included both selenium and TestNG from https://mvnrepository.com/
Remember to Clean and Build the project after any modification to the pom.xml After adding all dependencies, our final outcome will be as follows:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
<scope>compile</scope>
</dependency>
STEP 2: PACKAGE AND CLASS CREATION
In src main java, I created a package named sample_test and class Program_1.
![](https://static.wixstatic.com/media/1a239e_d324f0d43e504633a6152ce970fff589~mv2.png/v1/fill/w_125,h_167,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_d324f0d43e504633a6152ce970fff589~mv2.png)
After that, I created test cases with TestNG annotations to verify the name on this website https://www.numpyninja.com/ where an Assertion error is printed in the console as follows.
package sample_test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.time.Duration;
public class Program_1 {
WebDriver driver;// declaration
@BeforeMethod
public void setUp(){
System.setProperty("web-driver.chrome.driver","C:\\Codebase\\chromedriver_win32 (1)\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://www.numpyninja.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}
@Test
public void verifyName()
{
String actualTitle=driver.getTitle();
String expectedTitle="About | Numpy Ninja";// true
Assert.assertEquals(actualTitle, expectedTitle);
}
@Test
public void verifyInValidName()
{
String actualTitle=driver.getTitle();
String expectedTitle="Numpy Ninja";
Assert.assertEquals(actualTitle, expectedTitle)//Assertion error happened in this statement mentioning false
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
![](https://static.wixstatic.com/media/1a239e_0ec66bbb3a704cee89a6dd21c4449c53~mv2.png/v1/fill/w_49,h_21,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_0ec66bbb3a704cee89a6dd21c4449c53~mv2.png)
STEP 3: DEBUGGING THE ERROR
After brainstorming, let’s try to fix it.
What is assertion?
Types and methods of assertion statements?
Why do we require assertion?
How it relates to the exception?
What makes it different from throw (which is handled exception)?
Assertion Statements
assert is a keyword after JDK 1.4 onwards. It is of two types and it has different methods of statements.
assert boolean_result;//Very simple assert
assert boolean_result :"some_messages";// simple assert
//some method statements
assertEquals();// assertEquals method compares the expected result with that of the actual result and should say true
assertNotEquals();// validating the expected result with that of the actual result in negative scenario and should say true about not equal;
assertNull();//checks the object is null.
assertNotNull();// checks the object which is not null.
Debugging Java Programs to Solve why it occurs Once and for all with simple examples. We’ll do this in the context of a Java project. I created a package with class A.
Example 1: Very simple assert type
package package1;
public class A {
public static void main(String[] args)
{
System.out.println(1);
assert false;//
System.out.println(2);
}
}
Let's try to run. Actually, by default, no assert statement gets executed. in order to execute we need to supply one virtual machine argument explicitly.
Go to Run tab-> edit configuration-> Modify option -> Add VM option. In the VM option, enter -ea or -enable assertions--> click apply and ok.
-ea or -enable assertions
-da or -disable assertions
Now rerun the main method, assertion error gets in the main thread so the flow gets terminated.
![](https://static.wixstatic.com/media/1a239e_f0621f63ff894ba999368017871bf8fb~mv2.png/v1/fill/w_80,h_27,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_f0621f63ff894ba999368017871bf8fb~mv2.png)
Even though by default, every assert statement is disabled if you want you can specify explicitly disabling the assert statement with one virtual argument.
enable/disable assertions can be total execution wise
or it can be a particular package-wise and its sub-package-wise or a particular class-wise.
Raising assertion error, whenever business logic gets failed.
assert (boolean literal, expression, variable);
ex. assert false;//rule gets failed so raise the error.
assert true;// it executes successfully
By default, assert statements are not executing. enabling the argument -ea upon executing if it receives a false error supposed to be thrown and the flow gets terminated because we are not handling try, catch here. if true it gets passed.
package package1;
public class B {
public static void main(String[] args)
{
System.out.println(1);
assert true;
System.out.println(2);
}
}
![](https://static.wixstatic.com/media/1a239e_987f3347aab34b28a27e875d3ba27ac0~mv2.png/v1/fill/w_59,h_18,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_987f3347aab34b28a27e875d3ba27ac0~mv2.png)
Example 2: Simple assert type.
We need to follow the same steps when we try to run the class for every different scenario. Go to Run tab-> edit configuration-> Modify option -> Add VM option. In the VM option, enter -ea or -enable assertions--> click apply and ok.
Now rerun the main method, assertion error gets in the main thread so the flow gets terminated if it is false with some messages in the console.
package package1;
public class C {
public static void main(String[] args)
{
System.out.println(1);
assert false : "Something went wrong";
System.out.println(2);
}
}
![](https://static.wixstatic.com/media/1a239e_d86b201b53794bd7b57e1da0dbecb257~mv2.png/v1/fill/w_49,h_13,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_d86b201b53794bd7b57e1da0dbecb257~mv2.png)
I explored some more examples. it was exciting!! Never forget to explore.
int i = 10;
assert i == 10;// true.
int i = 10;
assert i = 10;//if we run this statement we get incompatible types: int cannot be converted to boolean
int i = 10;
assert i == 10 : ;//if we execute this we get this error java: illegal start of expression
//after: it can be literals,variables,method calling statements return other than void.
assert test();//calling test method
static boolean test()
{
return true;//boolean statement it executes successfully.
}
assert test();//Method should have return type boolean
static int test()// Only boolean, so error occurs.
{
return 10;
}
assert true : test();// method calling statement other than void.
static int test()
{
return 10;
}
assert true : test();
//java: 'void' type not allowed here so error occured.
static void test()
{
}
int assert = 10;
/*after jDK1.4 assert is a keyword cant be used as
variable,identifier will throw compilation error.*/
System.out.println(assert);
How it relates to exception handling and why it is compared with throw
Raising Assertion error when the business logic is violated. Not executing by default. | Raising exception error whenever the business condition is failed. Executes any time. |
By default it is disabled whenever we need it, we need to enable it explicitly. it is only for assertion error. | No way of disabling the throw statement. But it can be raised for any exception or error. |
We can't choose our own exception class and we can't specify the class name, it arises only assertion error. | throw can be any object of exception or object of error. throw keyword can be a new arithmetic exception, a new null pointer exception, or even it can throw a new assertion error class. |
Assert can be kept anywhere in the method. | throw can be the last statement in the current definition block. |
STEP 4: ERROR-FREE CODE
I think now, we are ready to fix the issue. isn't?
public void verifyInValidName()
{
String actualTitle=driver.getTitle();
String expectedTitle="Numpy Ninja";
Assert.assertNotEquals(actualTitle, expectedTitle);// it should say true, whenever the condition fails assertion should be thrown.
}
Here I am validating the not-equal scenario with the input given as not equal so the condition should say true.
![](https://static.wixstatic.com/media/1a239e_a85c440d547444a1a5c3d5c41c97596c~mv2.png/v1/fill/w_70,h_47,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_auto/1a239e_a85c440d547444a1a5c3d5c41c97596c~mv2.png)
So what we inferred?
Assertion helps to test the assumptions about the logic in the program to satisfy true or false conditions.
Only in the case of false, this error is thrown by JVM.
Equals() method is defined in the Object class in Java and used for checking the equality of two objects defined by business logic.
Actually, assertion led to the pathway to analyze what is an exception and how it is handled.
An exception is an error that happens at the time of execution of a program.
Try-catch: This method can catch Exceptions, which uses a combination of the try-and-catch keywords.
Multiple catches help us to handle every type of Exception separately with a separate block of code.
The throw keyword is used to throw an Exception to handle it in the run time.
printStackTrace(): This function prints stack trace, the name of the Exception, and other useful descriptions.
toString(): This function returns a text message describing the exception name and description.
getMessage(): Helps to display the description of the Exception.
It just goes to show that even the smallest findings can lead to significant discoveries.
Keep pushing forward and don’t be afraid to dive deeper!
How will you approach the error? Share your insights in the comment.
Happy Learning !!