Correspondants d’objets Hamcrest

Hamcrest Object Matchers

1. Vue d'ensemble

Hamcrest provides matchers for making unit test assertions simpler and more legible. Vous pouvez commencer à explorer certains des correspondants disponibleshere.

Dans ce rapide tutoriel, nous allons approfondir les correspondances d'objets.

2. Installer

Pour obtenir Hamcrest, nous avons juste besoin deadd the following Maven dependency to our pom.xml:


    org.hamcrest
    java-hamcrest
    2.0.0.0
    test

La dernière version de Hamcrest peut être trouvée surMaven Central.

3. Correspondants d'objets

Object matchers are meant to perform checks over object’s properties.

Avant d'examiner les correspondances, nous allons créer quelques beans pour rendre les exemples simples à comprendre.

Notre premier objet s'appelleLocation et n'a pas de propriétés:

public class Location {}

Nous nommerons notre deuxième beanCity et y ajouterons l'implémentation suivante:

public class City extends Location {

    String name;
    String state;

    // standard constructor, getters and setters

    @Override
    public String toString() {
        if (this.name == null && this.state == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append("Name: ");
        sb.append(this.name);
        sb.append(", ");
        sb.append("State: ");
        sb.append(this.state);
        sb.append("]");
        return sb.toString();
    }
}

Notez queCity étendLocation. Nous en profiterons plus tard. Commençons maintenant par les correspondances d'objets!

3.1. hasToString

Comme son nom l'indique, leshasToString method verifies that certain object has a toString method that returns a specific String:

@Test
public void givenACity_whenHasToString_thenCorrect() {
    City city = new City("San Francisco", "CA");

    assertThat(city, hasToString("[Name: San Francisco, State: CA]"));
}

Donc, nous créons unCity et vérifions que sa méthodetoString renvoie lesString que nous voulons. Nous pouvons aller plus loin et au lieu de vérifier l'égalité, recherchez une autre condition:

@Test
public void givenACity_whenHasToStringEqualToIgnoringCase_thenCorrect() {
    City city = new City("San Francisco", "CA");

    assertThat(city, hasToString(
      equalToIgnoringCase("[NAME: SAN FRANCISCO, STATE: CA]")));
}

Comme nous pouvons le voir,hasToString is overloaded and can receive both a String or a text matcher as a parameter. Donc, nous pouvons aussi faire des choses comme:

@Test
public void givenACity_whenHasToStringEmptyOrNullString_thenCorrect() {
    City city = new City(null, null);

    assertThat(city, hasToString(emptyOrNullString()));
}

Vous pouvez trouver plus d'informations sur les correspondances de textehere. Passons maintenant à la correspondance d’objets suivante.

3.2. typeCompatibleWith

Ce matcherrepresents an is-a relationship. Voici notre superclasseLocation en jeu:

@Test
public void givenACity_whenTypeCompatibleWithLocation_thenCorrect() {
    City city = new City("San Francisco", "CA");

    assertThat(city.getClass(), is(typeCompatibleWith(Location.class)));
}

Cela veut dire queCity est-aLocation, ce qui est vrai et ce test devrait réussir. Aussi, si nous voulions tester le cas négatif:

@Test
public void givenACity_whenTypeNotCompatibleWithString_thenCorrect() {
    City city = new City("San Francisco", "CA");

    assertThat(city.getClass(), is(not(typeCompatibleWith(String.class))));
}

Bien sûr, notre classeCity n'est pas unString.

Enfin, notez que tous les objets Java doivent réussir le test suivant:

@Test
public void givenACity_whenTypeCompatibleWithObject_thenCorrect() {
    City city = new City("San Francisco", "CA");

    assertThat(city.getClass(), is(typeCompatibleWith(Object.class)));
}

N'oubliez pas quethe matcher is consists of a wrapper over another matcher with the purpose of making the whole assertion more readable.

4. Conclusion

Hamcrest provides a simple and clean way of creating assertions. Il existe une grande variété de correspondants qui simplifient la vie de chaque développeur et rendent chaque projet plus lisible.

Et les matchers d'objet sont certainement un moyen simple de vérifier les propriétés de classe.

Comme toujours, vous trouverez la mise en œuvre complète surthe GitHub project.