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

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

 

9 thoughts on “TestNG Tutorials 13: Can An Interface have TestNG Methods? If Yes, How To Execute Them?

  1. Hi Amod, how are you able to define a body for the method in interface, I am getting an error to remove the body for the method in an interface which is correct. But in the post above, you have provided the body for the methods – staticMethod, DefaultMethod, beforeTestMethod and afterTestMethod, can you please comment on this….

    1. Hi Neha,
      In java 8, an interface can have concrete methods. Upgrade java version if its not 8

      1. Hi Amod, Thanks for the update but I selected Java 1.8 only for the project…..I verified in the eclipse under Windows>Preferences>InstalledJREs…let me know if I need to change anything else

Leave a Reply

Your email address will not be published. Required fields are marked *