Class InMemoryJndiContextFactory

java.lang.Object
org.dbunit.database.InMemoryJndiContextFactory
All Implemented Interfaces:
InitialContextFactory

public final class InMemoryJndiContextFactory extends Object implements InitialContextFactory
Test-only InitialContextFactory backed by a simple in-memory name-to-object map, so JndiDatabaseTester can be unit tested through a real InitialContext without a real JNDI provider or an extra test dependency.

Register an object under a unique name with bind(Object), then pass environment() (or an environment built from it) as the environment argument of the JndiDatabaseTester constructors so JNDI resolves this factory. Bindings are held in static maps for the JVM's lifetime; call unbind(String) from test cleanup (e.g. an @AfterEach method) for every name bind(Object) returned, so a long test run does not accumulate bound objects it no longer needs.

Since:
3.4.0
  • Constructor Details

    • InMemoryJndiContextFactory

      public InMemoryJndiContextFactory()
  • Method Details

    • bind

      public static String bind(Object value)
      Binds the given object under a fresh, unique name.
      Parameters:
      value - The object Context.lookup(String) should return.
      Returns:
      The unique name the object was bound under.
    • unbind

      public static void unbind(String name)
      Removes the given bound name and its lookup counter, so the previously bound object - and anything it holds, e.g. a test DataSource - becomes eligible for garbage collection. Call from test cleanup for every name bind(Object) returned.
      Parameters:
      name - A name previously returned by bind(Object).
    • lookupCount

      public static int lookupCount(String name)
      Returns how many times Context.lookup(String) has been called for the given bound name.
      Parameters:
      name - A name previously returned by bind(Object).
      Returns:
      The number of lookups observed so far.
    • environment

      public static Properties environment()
      Returns a JNDI environment that resolves InitialContext to this factory.
      Returns:
      A fresh, mutable Properties instance.
    • getInitialContext

      public Context getInitialContext(Hashtable<?,?> environment)
      Returns a proxy Context whose lookup(String) resolves names against BINDINGS (incrementing the matching LOOKUP_COUNTS entry) and whose close() is a no-op; any other Context method throws UnsupportedOperationException.
      Specified by:
      getInitialContext in interface InitialContextFactory
      Parameters:
      environment - Ignored; this factory only ever serves the in-memory bindings.
      Returns:
      The proxy Context.