Hamcrest for Kotlin

Overview

HamKrest - Hamcrest for Kotlin

A reimplementation of Hamcrest to take advantage of Kotlin language features.

Kotlin Build Status Maven Central

Note: as of version 1.4.0.0, you must add kotlin-reflect to the classpath to use HamKrest's reflective features.

When working in Kotlin, Hamkrest provides these benefits over using the Java Hamcrest library:

  • Kotlin's type system means that developers don't have to worry about getting the variance of generic signatures right. Variance is defined on the abstract Matcher type and Kotlin makes sure composition and subtyping work together the way you expect.

  • Syntactic sugar. You can negate a matcher with the ! operator and compose matchers with infix and and or functions:

    import com.natpryce.hamkrest.assertion.assert
          
    ...
          
    assertThat("xyzzy", startsWith("x") and endsWith("y") and !containsSubstring("a"))
  • Easier to extend. You can convert named unary predicates into matchers.

    val isBlank = Matcher(String::isBlank)
    
    assertThat(input, isBlank)

    As a shortcut, you can pass named functions to the assertThat, and, or and many other functions that take a matcher.

    assertThat(input, String::isBlank)

    You can also convert a named binary predicate and the second argument to a matcher for first argument, which works well for extension methods.

    fun String.hasLength(n: Int): Boolean = this.length == n
    
    val isTheRightLength = Matcher(String::hasLength, 8)
    
    assertThat(secretCode, isTheRightLength)

    You can use function and property references to match features of a value:

    val isLongEnough = has(String::length, greaterThan(8))
    
    assertThat(password, isLongEnough)

    All of these shortcuts produce good, human-readable diagnostics.

    You can customise how diagnostics are generated by creating a project-specific assert object.

More documentation

More detailed documentation of specific library features is in the docs/ directory.

Comments
  • Change the description of assertion errors so that IntelliJ shows the

    Change the description of assertion errors so that IntelliJ shows the "show difference" option in the console output.

    Hello,

    Love using hamkrest! but I have one gripe with it. IntelliJ doesn't show the "show difference" option when an assertion fails. This is quite handy when you're asserting the contents of data classes.

    A quick google shows that IntelliJ offers this functionality simply by checking a regular expression. Would it be possible to change the description strings so that IntelliJ shows the "show difference" option when using hamkrest?

    Kind regards,

    Ewout.

    opened by DenEwout 7
  • Please add support for containsInAnyOrder(T... items)

    Please add support for containsInAnyOrder(T... items)

    http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(T...)

    assertThat(listOf("foo", "bar"), containsInAnyOrder("bar", "foo"))

    opened by mcbeelen 6
  • added ContainsAllMatcher

    added ContainsAllMatcher

    I called the matcher containsAllbut there are couple problems with this name:

    • this matcher is based on IsIterableContainingInAnyOrder which means "equal iterables ignoring order of elements". It's not the same as equal Set objects and not the same as Collection.containsAll.
    • when used inside apply closure, it clashes with built-in containsAll function (see https://github.com/dkandalov/hamkrest/blob/c421c419294236336db8000bae1325321889208b/src/test/kotlin/com/natpryce/hamkrest/collection_matchers_tests.kt#L166-L166)

    I also have doubts that current mismatch description is good. Also passing custom "equality" matcher and nested iterables API looks a bit clunky.

    opened by dkandalov 6
  • assertThat should take vararg criteria

    assertThat should take vararg criteria

    While doing some checks on the same item that requires checking multiple things it occurred to me that this function:

    fun <T> assertThat(actual: T, criteria: Matcher<T>) {
        _assertThat(null, actual, criteria)
    }
    

    could be more convenient as:

    fun <T> assertThat(actual: T, vararg criteria: Matcher<T>) {
        criteria.foreach {_assertThat(null, actual, it) }
    }
    
    opened by dalewking 4
  • What is the status of Hamkrest?

    What is the status of Hamkrest?

    Hi,

    I stumbled across Hamkrest only recently, as I'd been incorrectly assuming that these were the only implementations of Hamcrest matchers. And I also see that Hamkrest has existed now for almost 3 years, which would seem to suggest that there are no plans to move it under the Hamcrest umbrella either.

    Can you tell me what Hamkrest's roadmap is please? I can't help but think of the Yammer/CodaHale/DropWizard metrics library here and wonder if the Hamkrest artifacts could ever mutate in such a way.

    Thanks, Chris

    opened by chrisr3 3
  • IntelliJ doesn't always show source

    IntelliJ doesn't always show source

    In IntelliJ, opening the 'External Libraries' view and finding Hamkrest, some of the 'files' are listed with a .class extension (CollectionMatchers.class) and some are not (CaseSensitity). The source for the latter is shown, the former just shows a decompiled version.

    It applies Maven and Gradle projects imported into IntelliJ, and certainly hampers my ability to work out how to use the library.

    opened by dmcg 3
  • Add assertAll?

    Add assertAll?

    This might be outside of the scope of this assertion library but a kotlin friendly way of declaring multiple assertions in a single test would be nice to add.

    I'm opening this issue due to the discussion in the Junit5:

    https://github.com/junit-team/junit5/issues/924

    Is this outside the scope of this project? If not, this method should probably throw the org.opentest4j.MultipleFailuresError which would require creating a dependency on opentest4j

    opened by JLLeitschuh 3
  • You haven't specified a license

    You haven't specified a license

    Trying to do my due diligence and document and credit all libraries I am using including noting the license, but I notice that you haven't actually declared a license in GitHub

    opened by dalewking 3
  • `assert` object is unable to be automatically imported by Intellij

    `assert` object is unable to be automatically imported by Intellij

    Probably because it's a Kotlin function as well. It's just a minor annoyance that I've been having. Does anyone have workarounds or alternatives that I don't know about? Using assertThat instead of assert.that works fine.

    opened by magneticflux- 2
  • Added anyPair matcher for working with maps

    Added anyPair matcher for working with maps

    What sort of an assertion framework doesn't have support for maps? Once I'd recovered from my shock at this blatant and malicious omission, I knocked something together quickly.

    Note the particular horrid cast. Better suggestions very welcome (Denton's only suggestion was 'invoke the Nat').

    Cheers 😄

    opened by jshiell 2
  • Available via Gradle?

    Available via Gradle?

    Hi, I'm trying to install by adding to my app's build.gradle:

    testCompile 'com.natpryce.hamkrest:1.4.2.0'

    but wasn't in your README, and it fails to resolve, and I found that this plugin is missing on plugins.gradle.org. I haven't authored a plugin myself but I believe this just requires publishing to plugins.gradle.org. That would make this library infinitely more useful. Thanks!

    opened by davidgoli 2
  • But why is it not Hamcrest compatible?

    But why is it not Hamcrest compatible?

    Right now there're tons of libs relying on Hamcrest matchers, such as rest-assured, which is also has Kotlin support.

    When I saw your library first time I was pretty surprised. It was until I realised that Hamkrest is not compatible with Hamcrest interfaces. That's really disappointing, as all of your syntactic sugar renders useless for me. The only question is why?

    Maybe is it possible to make your awesome lib compatible with Hamcrest?

    If not, don't you know any alternatives?

    opened by mitasov-ra 0
  • [Feature Request] Natural comparison matchers isGreaterThan isGreaterOrEqual isLessOrEqual isLessThan to invoke compareTo

    [Feature Request] Natural comparison matchers isGreaterThan isGreaterOrEqual isLessOrEqual isLessThan to invoke compareTo

    It would be nice to have comparison matchers that could be used like this:

    @Test
    fun comparisonExample() {
        val duration = getDurationFromSomewhare()
        assertThat(duration, isLessThan(Duration.ofSeconds(2)))
    }
    
    opened by christianhujer 0
  • Add workflow for Update Gradle Wrapper Action.

    Add workflow for Update Gradle Wrapper Action.

    Hey there 👋, first of all thanks for your work on HamKrest!

    I've got a suggested change: would you be willing to use this GitHub Action to automatically keep Gradle Wrapper updated to latest release?

    What does "Update Gradle Wrapper Action" do? It can be configured to run at scheduled intervals (e.g. daily or weekly) and will check whether the Wrapper script in the repo is up-to-date to the latest Gradle release: in case a new Gradle version is available, it will create a PR to update the Wrapper. And that's it!

    Why is that a good thing? Well, first of all it alleviates the chore of manually updating the Wrapper, as you got a task that keeps track of new Gradle releases for you! More importantly, it boosts security around the Wrapper update and usage processes: this actions verifies that the gradle-wrapper.jar file has not been tampered with (uses checksum comparison), and it sets the distributionSha256Sum property so that the new Gradle binary itself will be verified locally upon download.

    Where can I find more about? The README contains quite detailed information!

    In this PR I propose adding a new workflow which runs the action every day at midnight (but feel free to adjust the frequency as you prefer). I've verified it works correctly in my fork of the repo: as your Wrapper is already up-to-date in this moment, you can see here that the action detects no changes are needed. However, you can see an example of an automated PR in other projects using the action.

    The action is under active development, you can have a look at the list of inputs currently supported. There's new features coming up soon and if you'd like to request any particular change just let me know!

    I'd love to see the action used by HamKrest and I genuinely hope you can find this useful. Would love your feedback! ❤️

    opened by cristiangreco 0
  • Adding hamkrest as test dependency to multiplatform module

    Adding hamkrest as test dependency to multiplatform module

    Is it possible to add hamkrest as test dependency in multiplatform package?

    I am trying to do this commonTest { dependencies { implementation kotlin('test-common') implementation kotlin('test-annotations-common') implementation 'com.natpryce:hamkrest:1.7.0.0' } }

    but that doesn't work. I can see the lib in Intellij but classes are not accessible in tests

    opened by sith 4
  • hasSize overload for just taking an integer

    hasSize overload for just taking an integer

    Something that would just make writing test simpler:

    /**
     * Matches a collection with a size that is equal to [size].
     */
    fun hasSize(size: Int) = has(Collection<Any>::size, equalTo(size))
    
    opened by JLLeitschuh 0
Releases(1.7.0.0)
  • 1.7.0.0(Feb 16, 2019)

    A new way of extending how Hamkrest describes values in diagnostic messages: https://github.com/npryce/hamkrest/blob/master/docs/describe.md

    Removed the assert object and Asserter class, which was intended to let client code extend how Hamkrest describes values, but did not work. This is a backward incompatible change. Client code must be changed to call assertThat instead of assert.that. There are no other changes, so you can continue to use the 1.6.0.0 release while converting code to use assertThat, and then upgrade to 1.7.0.0.

    Source code(tar.gz)
    Source code(zip)
  • 1.6.0.0(Aug 24, 2018)

  • 1.4.0.0(Apr 21, 2017)

    • Reflectomagic works with Kotlin 1.1.1 (the kotlin-reflect library must be on the classpath)
    • The message can be passed as a function, so that it can be generated only when a failure occurs
    • The way that values are described in error messages is now customisable.
    Source code(tar.gz)
    Source code(zip)
Owner
Nat Pryce
Nat Pryce
Portable validations for Kotlin

Portable validations for Kotlin ✅ Type-safe DSL ?? Multi-platform support (JVM, JS) ?? Zero dependencies Installation For multiplatform projects: kotl

null 509 Dec 18, 2022
Powerful, elegant and flexible test framework for Kotlin with additional assertions, property testing and data driven testing

Kotest is a flexible and comprehensive testing tool for Kotlin with multiplatform support. To learn more about Kotest, visit kotest.io or see our quic

Kotest 3.8k Jan 3, 2023
mocking library for Kotlin

Kotlin Academy articles Check the series of articles "Mocking is not rocket science" at Kt. Academy describing MockK from the very basics of mocking u

MockK 4.8k Jan 3, 2023
Strikt is an assertion library for Kotlin intended for use with a test runner such as JUnit, Minutest, Spek, or KotlinTest.

Strikt is an assertion library for Kotlin intended for use with a test runner such as JUnit, Minutest, Spek, or KotlinTest.

Rob Fletcher 447 Dec 26, 2022
Fixtures for Kotlin providing generated values for unit testing

A tool to generate well-defined, but essentially random, input following the idea of constrained non-determinism.

Appmattus Limited 191 Dec 21, 2022
A Kotlin Android library for heuristics evasion that prevents your code from being tested.

EvadeMe An Android library for heuristics evasion that prevents your code from being tested. User Instructions Add the maven repository to your projec

Chris Basinger 29 Dec 26, 2022
Lightweight service for creating standalone mock, written in pure Kotlin with Netty container.

MockService The lightweight service for creating a standalone mock, written in pure Kotlin with Netty container. The service allows getting config fil

null 2 Oct 28, 2021
Proyecto de Kotlin y JPA sobre Hibernate, con algunos test usando JUnit 5 y Mockito.

Contactos Kotlin JPA Ejemplos de una aplicación de manejo de contactos con Kotlin y JPA. Usando para testear la aplicación JUnit 5 y Mockito. Almacena

José Luis González Sánchez 3 Sep 13, 2022
This is a sample API project for Rest Assured with Maven Kotlin DSL & JUnit 5

Kotlin-RestAssured Test Automation This is a sample API project for Rest Assured with Maven Kotlin DSL & JUnit 5 Introduction All the Test Cases kept

Dilshan Fernando 0 Dec 9, 2021
Android Sample Kotlin+ MVVM + Coroutines + Retrofit +Hilt+ Junit + Mockito

NTimes AppSample NY Times Most Popular Articles simple app to hit the NY Times Most Popular Articles API and show a list of articles, that shows detai

Amer Elsayed 0 Dec 27, 2021
Snapshot Testing framework for Kotlin.

KotlinSnapshot Snapshot Testing framework for Kotlin. What is this? Snapshot testing is an assertion strategy based on the comparision of the instance

Pedro Gómez 157 Nov 13, 2022
Automated tests using Rest-assured with Kotlin lang

Testes de API em Kotlin Pré-requisitos Instalar o Kotlin Ambiente Para executar os testes localmente, estou utilizando o ServeRest Link do Repo: https

Rafael Berçam 15 Dec 23, 2022
Selenium locators for Java/Kotlin that resemble the Testing Library (testing-library.com).

Selenium Testing Library Testing Library selectors available as Selenium locators for Kotlin/Java. Why? When I use Selenium, I don't want to depend on

Luís Soares 5 Dec 15, 2022
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs

Zipline This library streamlines using Kotlin/JS libraries from Kotlin/JVM and Kotlin/Native programs. It makes it possible to do continuous deploymen

Cash App 1.5k Dec 30, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

common sense OSS 0 Jan 20, 2022
Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in Kotlin with Jetpack Compose and a backed in Kotlin hosted on AppEngine.

Conferences4Hall Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in K

Gérard Paligot 98 Dec 15, 2022
🚀Plugin for Android Studio And IntelliJ Idea to generate Kotlin data class code from JSON text ( Json to Kotlin )

JsonToKotlinClass Hi, Welcome! This is a plugin to generate Kotlin data class from JSON string, in another word, a plugin that converts JSON string to

Seal 2.8k Jan 3, 2023