top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

java. lang.AssertionError-Let's try to tackle it.


Why start with AssertionError?


When we try to start something new we will think a lot about each and everything. Though a lot of topics are there sometimes small findings make us dig further. When I try to demonstrate a simple testing framework with selenium and TestNG, I got an error message in the console "java. lang.AssertionError".Even though it is a little one, It creates a curiosity to enter deep dive into it and came out with exciting observations.




I am using IntelliJ IDE for my practice. Initially, I created a Maven project, and I add the required dependencies in the pom.xml file. Here I added both selenium and TestNG from https://mvnrepository.com/

<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>

In src main java, I created a package sample_test and class Program_1.


So 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.


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();
    }

}

Lets us try to fix it quite sometime after analyzing 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.


  • 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);
    }
}

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);
    }

}

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.

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.


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


How will you approach the error? Share your insights in the comment.


Happy Learning !!









76 views0 comments

Recent Posts

See All
bottom of page