TestNG Tutorials 13: Can An Interface have TestNG Methods? If Yes, How To Execute Them? | Make Selenium Easy

Hello Folks,

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.

Updated Interface:

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.

Regenerate testng.xml:

Console output:

Finally it ran all Test annotated method.

Let’s update Interface as below and run:

Output:

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. #ThanksForReading

#HappySelenium