Java tutorial
/* * Copyright 2014 Objectos, Fbrica 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 marcio.endo@objectos.com.br (Marcio Endo) */ class MatcherToStringEqualToResource<T> extends TypeSafeMatcher<T> { 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<String> actualLines = readLines(item); URL resource = Resources.getResource(item.getClass(), resourceName); List<String> expectedLines = Resources.readLines(resource, Charsets.UTF_8); lineAssert = LineAssert.get(actualLines, expectedLines); return lineAssert.valid(); } catch (Exception e) { throw Throwables.propagate(e); } } List<String> readLines(T object) throws Exception { String string = object != null ? object.toString() : ""; return Splitter.on(StandardSystemProperty.LINE_SEPARATOR.value()).splitToList(string); } }