3

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!

user1567909
  • 1,450
  • 2
  • 14
  • 24
  • possible duplicate of [How do Java method annotations work in conjunction with method overriding?](http://stackoverflow.com/questions/10082619/how-do-java-method-annotations-work-in-conjunction-with-method-overriding) – PM 77-1 Aug 21 '14 at 01:28

2 Answers2

1

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();
  }
}
Andrey M
  • 53
  • 7
  • This only works if OP is OK with both methods being invoked. I believe the question is to have `derivedClass`'s method overload `superClass`'s. – John B Aug 21 '14 at 13:58
  • Yes, you can override super method and JUnit will call it. But you cannot put `@BeforeClass` annotation on overloaded method. It's okay for JAVA compiler but JUnit requirements is method anotated with `@BeforeClass` should be static. – Andrey M Aug 21 '14 at 23:09
  • My point is that if the OP wanted to override the behavior, the correct solution is not to fix the use of `@BeforeClass`. – John B Aug 22 '14 at 10:40
1

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.

John B
  • 32,493
  • 6
  • 77
  • 98