Search code examples
javaannotationstestng

Disable test class using annotation transformer


I am trying to disable a Test Class that contains test methods, based on a condition set in an excel spreadsheet. I have implemented an Annotation Transformer that disables the test class based on the condition, however it does not seem to be able to disable the desired test class, instead it is failing to execute. I have tested the Annotation Transformer using a test method, and it worked in disabling it. Below is my Annotation Transformer.

    int count=0;
    
    @Override
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
        
        
        try {
            if(count==0) {
                TestUtilities.getRunStatus();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        for(int i=0; i<TestUtilities.testCases.size(); i++) {
            if(testClass.getName().equalsIgnoreCase(TestUtilities.testCases.get(i)))
                {   
                if(TestUtilities.runStatus.get(i).equalsIgnoreCase("no")) {
                    
                    annotation.setEnabled(false);                           //sets the enabled parameter for all the test cases based on the excel sheet input
                    break;
                }
            } 
        }

        count++;
        
        
    }
}

Solution

  • Since the annotation transformer caters to multiple conditions you would need to first check for null values before you start interacting with the parameters.

    • Class testClass - This is NON Null only if the @Test annotation was found on top of a class (Class level annotations)
    • Constructor testConstructor - This is NON Null only if the @Test annotation was found on top a class's constructor
    • Method testMethod - This is NON Null only if the @Test annotation was found on top of a method.

    So if all your methods have @Test annotation then you would need to use perhaps reflection to figure out the class to which a method belongs to and then add your logic of inclusion/exclusion accordingly.