8

I want to run this line of code:

assertThat(contextPin.get(), equalTo(pinPage.getPinObjFromUi()));

but I want to print to the log be informative

meaning that I could know which fields were not equal.

So I have thought to implement a matcher.

I have googled it, but couldn't write it properly

as my method couldn't get the actual and expected objects together.

here is my code:

how can I write it clean?

public class PinMatcher extends TypeSafeMatcher<Pin> {

    private Pin actual;
    private Object item;

    public PinMatcher(Pin actual) {
        this.actual = actual;
    }

    @Override
    protected boolean matchesSafely(Pin item) {
        return false;
    }

    @Override
    public void describeTo(Description description) {

    }

//cannot override this way
    @Override
    public boolean matches(Object item){
       assertThat(actual.title, equalTo(expected.title));
return true;
    }

//cannot access actual when called like this:
// assertThat(contextPin.get(), new PinMatcher.pinMatches(pinPage.getPinObjFromUi()));
    @Override
    public boolean pinMatches(Object item){
        assertThat(actual.title, equalTo(expected.title));
return true;
    }
}
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157
  • 1
    Please look at the source code of some built-in Hamcrest matcher. They show you how to override matchesSafely and describeTo. – Stefan Birkner Jul 18 '14 at 20:02

2 Answers2

6

Try something more like this:

package com.mycompany.core;

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


public class PinMatcher extends TypeSafeMatcher<Pin> {

    private Pin actual;

    public PinMatcher(Pin actual) {
        this.actual = actual;
    }

    @Override
    protected boolean matchesSafely(Pin item) {
        return actual.title.equals(item.title);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("should match title ").appendText(actual.title);

    }
}
Sergio
  • 3,317
  • 5
  • 32
  • 51
schnitz
  • 190
  • 2
  • 9
5

Your matches should receive expected in the constructor and compare it against the "actual value" item parameter passed to matchesSafely. You should not override matches.

This will line up with what assertThat expects:

assertThat(actual, matcher-using-expected);

I think the string-based matchers are type-safe and will provide a good example.

David Harkness
  • 35,992
  • 10
  • 112
  • 134