1

I'm automating some checks with JUnit. Almost all require that the user is logged in. I already have a @Test which performs the login action but how can I instruct JUnit that this login is performed only once before all other tests?

I know that @BeforeClass could be used but this would mean that I need to call it for every further class.

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192
  • did you check this answers: https://stackoverflow.com/questions/12087959/junit-run-set-up-method-once – Ori Marko Jun 21 '18 at 10:25
  • As far as I can tell the linked question is about all tests within the same class. However I'm looking for something that runs a test before all other tests in all other classes. – Robert Strauch Jun 21 '18 at 10:32
  • I think you can't share the state of 'logged in' between several Unit test classes, so if your unit test requires a login to your app you should use `@BeforeClass` in every test. If all your JUnit tests need to log in, maybe you should think of writing more Unit and less Integration tests (with your Security provider enabled). Which Security framework are you using? – rieckpil Jun 22 '18 at 20:49

1 Answers1

4

JUNIT 4

You can create parent class with only one test. And extend all classes from it.

private static final AtomicBoolean REQUIRES_LOGIN = new AtomicBoolean(true);

 @Test
 void setup() {
   if (REQUIRES_LOGIN.getAndSet(false)) {
     System.out.println("Doing login here");
   }
 }

JUNIT 5

You can register global extension in following file.

META-INF/services/org.junit.jupiter.api.extension.Extension
demo.api.BeforeAllExtension

Extension class:

public class BeforeAllExtension implements BeforeAllCallback {

     private static final AtomicBoolean REQUIRES_LOGIN = new AtomicBoolean(true);

    @Override
    public void beforeAll(ExtensionContext extensionContext) {
        if (REQUIRES_LOGIN.getAndSet(false)) {
            System.out.println("Doing login here");
        }
    }
}

Checkout how to turn on extension registration here

Ivan Lymar
  • 2,180
  • 11
  • 26