简体   繁体   中英

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));
     }
}

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM