Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement a hamcrest matcher

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;
    }
}
like image 978
Elad Benda2 Avatar asked Jul 17 '14 16:07

Elad Benda2


People also ask

Is hamcrest a matcher?

Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.

Does JUnit include hamcrest?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.


1 Answers

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);

    }
}
like image 88
schnitz Avatar answered Dec 06 '22 04:12

schnitz