Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a JUnit annotation?

I have a method I call in my superclass like so:

public class superClass {
  @Before
  void createDriver(){
    driverFactory = new FirefoxDriverFactory();
  }
  ...
}

However, in my test suite specifically which inherits from the super class, I want it so that I can run my test with the @BeforeClass annotation and not the @Before annotation. I'm not sure, but is it possible to override the @Before annotation or not? I tried the following:

public class derivedClass extends superClass{
  @Override
  @BeforeClass
  void createDriver(){
    driverFactory = new FirefoxDriverFactory();
  }
}

But I get an error that says that the createDriver() method must be static and I must remove the @Override annotation. Is it possible to Override an annotation as opposed to a function? I was just wondering. Thanks!

like image 543
user1567909 Avatar asked Feb 27 '26 08:02

user1567909


2 Answers

The issue is not in annotation overrides. JUnit requires @BeforeClass method to be static:

public class derivedClass extends superClass{

  @BeforeClass
  public static void beforeClass(){
   driverFactory = new FirefoxDriverFactory();
  }
}
like image 82
Andrey M Avatar answered Mar 01 '26 21:03

Andrey M


I think this is what you might be looking for...

public class superClass {
  @Before
  void createDriver(){
    driverFactory = new FirefoxDriverFactory();
  }
  ...
}

public class derivedClass extends superClass{
  @Override
  void createDriver(){
    driverFactory = new FirefoxDriverFactory();
  }
}

JUnit should find superClass.createDriver() via the annotation. However, when this method is invoked on an instance of derivedClass the actual method that should be run is derivedClass.createDriver() since this method overloads the other. Try it and let us know.

like image 32
John B Avatar answered Mar 01 '26 20:03

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!