Package org.apache.flink.testutils.junit
Class SharedObjects
java.lang.Object
org.junit.rules.ExternalResource
org.apache.flink.testutils.junit.SharedObjects
- All Implemented Interfaces:
org.junit.rules.TestRule
@NotThreadSafe
public class SharedObjects
extends org.junit.rules.ExternalResource
This rule allows objects to be used both in the main test case as well as in UDFs by using
serializable
SharedReferences. Usage:
@Rule
public final SharedObjects sharedObjects = SharedObjects.create();
@Test
public void test() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SharedReference<Queue<Long>> listRef = sharedObjects.add(new ConcurrentLinkedQueue<>());
int n = 10000;
env.setParallelism(100);
env.fromSequence(0, n).map(i -> listRef.get().add(i));
env.execute();
assertEquals(n + 1, listRef.get().size());
assertEquals(
LongStream.rangeClosed(0, n).boxed().collect(Collectors.toList()),
listRef.get().stream().sorted().collect(Collectors.toList()));
}
The main idea is that shared objects are bound to the scope of a test case instead of a class. That allows us to:
- Avoid all kinds of static fields in test classes that only exist since all fields in UDFs need to be serializable.
- Hopefully make it easier to reason about the test setup
- Facilitate to share more test building blocks across test classes.
- Fully allow tests to be rerun/run in parallel without worrying about static fields
Note that since the shared objects are accessed through multiple threads, they need to be thread-safe or accessed in a thread-safe manner.
-
Method Summary
Modifier and TypeMethodDescription<T> SharedReference<T>add(T object) Adds a new object to thisSharedObjects.protected voidafter()protected voidbefore()static SharedObjectscreate()Creates a new instance.booleaninthashCode()Methods inherited from class org.junit.rules.ExternalResource
apply
-
Method Details
-
create
Creates a new instance. Usually that should be done inside a JUnit test class as an instance-field annotated withRule. -
add
Adds a new object to thisSharedObjects. Although not necessary, it is recommended to only access the object through the returnedSharedReference. -
before
- Overrides:
beforein classorg.junit.rules.ExternalResource- Throws:
Throwable
-
after
protected void after()- Overrides:
afterin classorg.junit.rules.ExternalResource
-
equals
-
hashCode
public int hashCode()
-