Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 31 junit 5 Stores are hierarchical because a store is created for each extension context which means there is one store per node in the test tree Each test container or test method has its own store In much the same way as nodes inherit extensions stores inherit state To be more precise when a node creates a store the node hands the store a reference to its parents store Thus for example the store belonging to a test method holds a reference to the store belonging to the test class that contains the method Upon queries but not edits a store first checks its own content before delegating to its parent store This makes a stores state readable to all child stores Regarding having a key value data structure a store is a simplified map in which keys and values can be of any type Here are the most essential methods interface Store void put Object key Object value V V get Object key Class V requiredType V V remove Object key Class V requiredType The methods get and remove take a type token to prevent clients from littering their code with casts There is no magic there the store simply does the casts internally Overloaded methods without type tokens exist as well Stateless benchmarks To make the benchmark extension stateless I need a couple of things A namespace for the extension to access a store A key for the launch time The ability to write to and read from the store instead of from a field For the first two I declare two constants private static final Namespace NAMESPACE Namespace create org codefx Benchmark private static final String LAUNCH_ TIME_ KEY LaunchTime Reading and writing are two simple methods private static void storeNowAsLaunchTime ExtensionContext context context getStore NAMESPACE put LAUNCH_ TIME_ KEY currentTimeMillis private static long loadLaunchTime ExtensionContext context return context getStore NAMESPACE get LAUNCH_ TIME_ KEY long class With these methods I replace the access to the field launchTime which can subsequently be removed The methods executed before and after each test now look as follows @ Override public void beforeTestExecution TestExtensionContext context storeNowAsLaunchTime context @ Override public void afterTestExecution TestExtensionContext context long launchTime loadLaunchTime context long runtime currentTimeMillis launchTime print context getDisplayName runtime
You must have JavaScript enabled to view digital editions.