All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.wiremock.spring.internal.Store Maven / Gradle / Ivy

There is a newer version: 2.2.0
Show newest version
package org.wiremock.spring.internal;

import com.github.tomakehurst.wiremock.WireMockServer;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;

/**
 * Stores references to the instances of {@link WireMockServer} associated with Spring application
 * context.
 *
 * @author Maciej Walkowiak
 */
enum Store {
  INSTANCE;

  private static final Logger LOGGER = LoggerFactory.getLogger(Store.class);

  private final Map> store =
      new ConcurrentHashMap<>();

  WireMockServer findWireMockInstance(ApplicationContext applicationContext, String name) {
    return resolve(applicationContext).get(name);
  }

  WireMockServer findRequiredWireMockInstance(ExtensionContext extensionContext, String name) {
    WireMockServer wiremock = resolve(extensionContext).get(name);

    if (wiremock == null) {
      throw new IllegalStateException(
          "WireMockServer with name '"
              + name
              + "' not registered. Perhaps you forgot to configure it first with @ConfigureWireMock?");
    }

    return wiremock;
  }

  void store(ApplicationContext applicationContext, String name, WireMockServer wireMockServer) {
    resolve(applicationContext).put(name, wireMockServer);
  }

  Collection findAllInstances(ExtensionContext extensionContext) {
    return resolve(extensionContext).values();
  }

  private Map resolve(ExtensionContext extensionContext) {
    return resolve(SpringExtension.getApplicationContext(extensionContext));
  }

  private Map resolve(ApplicationContext applicationContext) {
    LOGGER.info("Resolving store from context: {}", applicationContext.getId());
    return store.computeIfAbsent(applicationContext, ctx -> new ConcurrentHashMap<>());
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy