willy
willy

Reputation: 255

sharing store data between extensions in JUNIT5

Is there anyway we can share data between different extensions in JUNIT 5 using store

Example

public class Extension1{
     beforeAllCallback(){
          getStore(GLOBAL).put(projectId,"112");
     }
}

public class Extension2{
     beforeTestExecutionCallback(){
          System.out.println("projectId="+getStore(GLOBAL).get(projectId));
     }
}

Upvotes: 0

Views: 2403

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31247

Yes, two extensions can share state via the Store as follows.

Note, however, that you may wish to store the shared state in the root context Store if you want the state to be accessible across test classes.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;

@ExtendWith({ Extension1.class, Extension2.class })
public class Tests {

    @Test
    void test() {
        // executing this results in the following being printed to SYS_OUT.
        // PROJECT_ID=112
    }
}

class Extension1 implements BeforeAllCallback {

    public static final String PROJECT_ID = Extension1.class.getName() + ".PROJECT_ID";

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        context.getStore(Namespace.GLOBAL).put(PROJECT_ID, "112");
    }
}

class Extension2 implements BeforeTestExecutionCallback {

    @Override
    public void beforeTestExecution(ExtensionContext context) throws Exception {
        System.out.println("PROJECT_ID=" + context.getStore(Namespace.GLOBAL).get(Extension1.PROJECT_ID));
    }
}

Upvotes: 6

Related Questions