We talked about TestNG class in previous post. Can we declare and define TestNG annotated methods in an Interface? We will learn now.
As per Java 8, An interface can have abstract methods, default methods and static methods.
Let’s create an Interface with TestNG annotated abstract methods and observe what happens:
An interface with TestNG annotated methods:
You can see there is no error messages. It means that we can have TestNG annotated methods in an interface.
Let’s create a testng.xml for above interface:
You can see that testng.xml is generated by putting interface name “InterfaceTestNGMethods” in class tag. So, you can generate a testng.xml for an interface which has TestNG @Test annotated method.
Now let’s run it as testng test:
You can see count of tests run is zero. Let’s assume as of now that @Test annotated method is an abstract method in interface so that is not included in test run.
Now, add a default and static @Test annotated method in interface and run it.
There is no need to regenerate testng.xml. We run same previously generated testng.xml and observe output:
Again same output as previous run. This time you have concrete Test annotated methods but it is not run by TestNG.
Let’s create an implemented class of above interface.
I added a new @Test method in driver class so that testng.xml can include this class otherwise you need to manually add class name in testng.xml.
Finally it ran all Test annotated method.
Let’s update Interface as below and run:
You can notice all methods ran successfully.
So, an interface can have TestNG annotated methods in it but you require an implemented class of interface to run it.
Hope you learnt new thing today.
More about TestNG in upcoming posts. Stay tuned.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
Author: Amod Mahajan
My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning