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

com.codepoetics.fluvius.test.matchers.AMap Maven / Gradle / Ivy

There is a newer version: 1.10
Show newest version
package com.codepoetics.fluvius.test.matchers;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;

import java.util.HashMap;
import java.util.Map;

public final class AMap extends TypeSafeDiagnosingMatcher> {

  public static  AMap of(Class keyClass, Class valueClass) {
    return new AMap<>(new HashMap>());
  }

  public static  AMap containing(K key, Matcher valueMatcher) {
    Map> expectedContents = new HashMap<>();
    expectedContents.put(key, valueMatcher);
    return new AMap<>(expectedContents);
  }

  public static  AMap containing(Map values) {
    Map> expectedContents = toExpectationMap(values);
    return new AMap<>(expectedContents);
  }

  private static  Map> toExpectationMap(Map values) {
    Map> expectedContents = new HashMap<>();
    for (Map.Entry entry : values.entrySet()) {
      expectedContents.put(entry.getKey(), Matchers.equalTo(entry.getValue()));
    }
    return expectedContents;
  }

  private final Map> expectedContents;

  public AMap with(K key, V value) {
    return with(key, Matchers.equalTo(value));
  }

  public AMap with(K key, Matcher valueMatcher) {
    expectedContents.put(key, valueMatcher);
    return this;
  }

  public AMap withValues(Map additionalValues) {
    return with(toExpectationMap(additionalValues));
  }

  public AMap with(Map> additionalMatchers) {
    expectedContents.putAll(additionalMatchers);
    return this;
  }

  private AMap(Map> expectedContents) {
    this.expectedContents = expectedContents;
  }

  @Override
  protected boolean matchesSafely(Map kvMap, Description description) {
    boolean matches = true;

    for (Map.Entry> entry : expectedContents.entrySet()) {
      if (!entry.getValue().matches(kvMap.get(entry.getKey()))) {
        matches = false;
        IndentationControl.newline(description).appendText(entry.getKey().toString()).appendText(": ");
        entry.getValue().describeMismatch(kvMap.get(entry.getKey()), description);
      }
    }

    return matches;
  }

  @Override
  public void describeTo(Description description) {
    if (expectedContents.isEmpty()) {
      description.appendText("A map");
      return;
    }

    description.appendText("A map with:");
    IndentationControl.indent();
    for (Map.Entry> entry : expectedContents.entrySet()) {
      IndentationControl.newline(description).appendText(entry.getKey().toString()).appendText(": ").appendDescriptionOf(entry.getValue());
    }
    IndentationControl.outdent();
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy