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

br.com.objectos.testing.MatcherToStringEqualToResource Maven / Gradle / Ivy

There is a newer version: 0.9.0
Show newest version
/*
 * Copyright 2014 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.testing;

import java.net.URL;
import java.util.List;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import com.google.common.base.Throwables;
import com.google.common.io.Resources;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

/**
 * @author [email protected] (Marcio Endo)
 */
class MatcherToStringEqualToResource extends TypeSafeMatcher {

  private final String resourceName;

  private LineAssert lineAssert;

  public MatcherToStringEqualToResource(String resourceName) {
    this.resourceName = resourceName;
  }

  @Override
  public void describeTo(Description description) {
    String msg = String.format("contents equalTo resource at '%s'", resourceName);
    description.appendText(msg);
  }

  @Override
  protected void describeMismatchSafely(T item, Description mismatchDescription) {
    mismatchDescription.appendDescriptionOf(lineAssert);
  }

  @Override
  protected boolean matchesSafely(T item) {
    try {
      List actualLines = readLines(item);
      URL resource = Resources.getResource(item.getClass(), resourceName);
      List expectedLines = Resources.readLines(resource, Charsets.UTF_8);
      lineAssert = LineAssert.get(actualLines, expectedLines);
      return lineAssert.valid();
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }

  List readLines(T object) throws Exception {
    String string = object != null ? object.toString() : "";
    return Splitter.on(StandardSystemProperty.LINE_SEPARATOR.value()).splitToList(string);
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy