Class SharedRandomExtension

java.lang.Object
io.github.cjstehno.testthings.junit.SharedRandomExtension
All Implemented Interfaces:
org.junit.jupiter.api.extension.AfterEachCallback, org.junit.jupiter.api.extension.BeforeEachCallback, org.junit.jupiter.api.extension.Extension

public class SharedRandomExtension extends Object implements org.junit.jupiter.api.extension.BeforeEachCallback, org.junit.jupiter.api.extension.AfterEachCallback
A JUnit test extension used to test randomized scenarios in a way that removes the randomness. This extension will only work with classes that use the SharedRandom class to provide their randomization.

The extension will set a known seed value on the random generator so that it is no longer random. By default, a shared known seed will be used (see DEFAULT_KNOWN_SEED); however, this may be overridden by a configured value in your test class.

You can specify your own seed value by adding a field to your class with the signature private static final long KNOWN_SEED = <your-value> to your test class. This provided value will be used instead of the default (it does not have to be "private").

Alternately, if your test method is annotated with the ApplySeed annotation, its value will be used as the seed for that test method.

The random generator is reset after each test by setting the seed to the current nanoTime() value (i.e. making it "random" again). Note: In case you are not aware, the seed-based random number generation is not really random - if you use the same seed, you get the same "random" values in the same order, which is the basis for this method of testing.

  • Field Details

    • DEFAULT_KNOWN_SEED

      public static long DEFAULT_KNOWN_SEED
      The default known seed value - should be good enough for most cases. You can override this default by providing a static final long KNOWN_SEED field with your value.
  • Constructor Details

    • SharedRandomExtension

      public SharedRandomExtension()
  • Method Details

    • beforeEach

      public void beforeEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
      Specified by:
      beforeEach in interface org.junit.jupiter.api.extension.BeforeEachCallback
      Throws:
      Exception
    • afterEach

      public void afterEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
      Specified by:
      afterEach in interface org.junit.jupiter.api.extension.AfterEachCallback
      Throws:
      Exception