Inheritance of class annotations in TestNG

Recently Oliver Fischer introduced TestNG at the Berlin-Brandenburg JUG. At one point there was an interesting discussion with the audience about class level annotations. Why should they be used? You can annotate a class like this:

@Test
public class Foo 
{
...

Now every public method in this class is considered a test method. Several people in the audience mentioned that they would still prefer to mark the test explicitly. This is just more readable. But if so, what might be a good reason to use class level annotations?

One very nice characteristic of class level annotations is that they can be inherited. Let’s assume you want several classes in a specific testgroup. What you don’t want to do is to annotate each and every test method with @Test(groups = {“MyTestGroup”}). This is simply not DRY. Using inheritance, you can instead create a base-class like this:

@Test(groups = {"MyTestGroup"})
public class BaseClass 
{
...

Now each test class that should be in this group can just extend BaseClass.

public class MyTestClass extends BaseClass 
{
...

Every public method in these classes is a test method and they belong to the group MyTestGroup. You probably still want to add the @Test annotation to each of the methods for readability. The group assignment is still valid.

What other ideas do you have for making use of annotation inheritance in TestNG?

Be Sociable, Share!
  1. Rahul says:

    could you enplane class level attributes and method level attributes for @Test

  1. There are no trackbacks for this post yet.

Leave a Reply