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 serializableSharedReference
s. 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
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description <T> SharedReference<T>
add(T object)
Adds a new object to thisSharedObjects
.protected void
after()
protected void
before()
static SharedObjects
create()
Creates a new instance.boolean
equals(Object o)
int
hashCode()
-
-
-
Method Detail
-
create
public static SharedObjects create()
Creates a new instance. Usually that should be done inside a JUnit test class as an instance-field annotated withRule
.
-
add
public <T> SharedReference<T> add(T object)
Adds a new object to thisSharedObjects
. Although not necessary, it is recommended to only access the object through the returnedSharedReference
.
-
before
protected void before() throws Throwable
- Overrides:
before
in classorg.junit.rules.ExternalResource
- Throws:
Throwable
-
after
protected void after()
- Overrides:
after
in classorg.junit.rules.ExternalResource
-
-