Code Monkey home page Code Monkey logo

cactoos-matchers's Introduction

Managed by Zerocracy Donate via Zerocracy

EO principles respected here DevOps By Rultor.com

Build Status Javadoc PDD status Maven Central License

Test Coverage SonarQube

What it is

cactoos-matchers is an object-oriented wrapper around hamcrest's matchers.

Principles

Design principles behind cactoos-matchers.

How to use

This library depends on cactoos and hamcrest. Get the latest version here:

<dependency>
  <groupId>org.llorllale</groupId>
  <artifactId>cactoos-matchers</artifactId>
  <version>${version}</version>
</dependency>

Java version required: 1.8+.

cactoos-matchers versus Hamcrest + JUnit

cactoos-matchers Hamcrest (static method) Hamcrest (object) JUnit
Assertion MatcherAssert.assertThat - Assert.assertThat
Throws - - @expected + ExpectedException
EndsWith Matchers.endsWith StringEndsWith -
StartsWith Matcers.startsWith StringStartsWith -
TextIs Matchers.is IsEqual -
HasLines - - -
MatchesRegex - - -
TextHasString Matchers.stringContainsInOrder StringContains -
FuncApplies - - -
HasValues Matchers.containsInAnyOrder IsIterableContainingInAnyOrder -
HasValuesMatching Matchers.containsInAnyOrder IsIterableContainingInAnyOrder -
InputHasContent - - -
IsTrue - - Assert.assertTrue
Matches - - -
RunsInThreads - - -
ScalarHasValue - - -

How to use

Use our matchers inside your JUnit @Test case. We also provide Assertion<T> in which you can compose the behavior under test and the test case's matcher, and attempt to affirm it.

We provide matchers for several different domains:

Text

Examples:

@Test
public void textHasPrefix() {
  final String prefix = "Application startup";
  new Assertion<>(
    "must have the prefix",
    () -> new TextOf(new File("some.log")),
    new StartsWith(prefix)
  ).affirm();
}  

@Test
public void csvLineHasCorrectFormat() throws Exception {
  final String fields = "^[^|]+|[^|]+|[^|]+$";
  new Assertion<>(
    "must match the expected pattern",
    () -> new FirstOf<>(
      line -> true,
      new SplitText(
        new TextOf(new File("report.csv")),
        "\n"
      )
    ).value(),
    new MatchesRegex(fields)
  ).affirm();
}

@Test
public void textIsBlank() {
  new Assertion<>(
    "must be blank",
    () -> new TextOf(new File("records.txt")),
    new IsBlank()
  ).affirm();
}

Concurrency

Examples:

RunsInThreads

/**
 * Want some assurance that your object is thread-safe?
 */
@Test
public void threadSafety() {
  new Assertion<>(
    "must be able to modify the map concurrently",
    () -> map -> {
      boolean success = true;
      try {
        map.forEach(
          (key, value) -> {
            map.remove(key);
            final Random r = new Random();
            map.put(r.nextInt(), r.nextInt());
          }
        );
      } catch (ConcurrentModificationException ex) {
        success = false;
      }
      return success;
    },
    new RunsInThreads<>(new ConcurrentHashMap<>(), 100)
  ).affirm();
}

Matching errors

Examples:

@Test
public void throwIllegalArgumentExceptionIfLessThan10() throws Exception {
  final Func<Integer, Integer> test = input -> {
    if (input < 10) {
      throw new IllegalArgumentException();
    }
    return input * 10;
  };
  new Assertion<>(
    "must throw illegalargumentexception if input is less than 10",
    () -> test.apply(5),
    new Throws(IllegalArgumentException.class)
  ).affirm();
}

Meta-matching: a matcher to test your matchers

Examples:

Use Matches to test matchers themselves:

@Test
public void matchExactString() {
  new Assertion<>(
    "must match the exact text",
    () -> new TextIs("abc"),          // matcher being tested
    new Matches<>(new TextOf("abc"))  // reference against which the matcher is tested
  ).affirm();
}

How to contribute?

Just fork the repo and send us a pull request.

Make sure your branch builds without any warnings/issues:

mvn clean install -Pqulice

Note: Checkstyle is used as a static code analyze tool with checks list in GitHub precommits.

Contributors

License (MIT)

Copyright (c) for portions of project cactoos-matchers are held by Yegor Bugayenko, 2017-2018, as part of project cactoos. All other copyright for project cactoos-matchers are held by George Aristy, 2018.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cactoos-matchers's People

Contributors

dgroup avatar llorllale avatar rultor avatar borysfan avatar sharpler avatar paulodamaso avatar jsoroka avatar victornoel avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.