Skip to content

Commit

Permalink
Add an infix variant of shouldNotBeNull that accepts a block (#4060)
Browse files Browse the repository at this point in the history
This allows for some syntactic sugar when dealing with the non-null
value.

Signed-off-by: Sebastian Schuberth <sschuberth@gmail.com>
  • Loading branch information
sschuberth committed Jun 4, 2024
1 parent 77cf524 commit 2cd159d
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
3 changes: 2 additions & 1 deletion documentation/docs/assertions/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ Matchers provided by the `kotest-assertions-core` module.
| `obj.shouldBeTypeOf<T>()` | Asserts that the given reference is exactly of type T. Subclass will fail. Ie, `1 should beOfType<Number>` would fail because although 1 _is_ a Number, the runtime type is not Number. |
| `obj.shouldBeInstanceOf<T>()` | Asserts that the given reference is of type T or a subclass of T. |
| `obj.shouldHaveAnnotation(annotationClass)` | Asserts that the object has an annotation of the given type. |
| `obj.shouldBeNull()` | Asserts that a given reference is null.|
| `obj.shouldBeNull()` | Asserts that a given reference is null. |
| `obj shouldNotBeNull { block }` | Asserts that a given reference is not null. |


| Comparables ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1739,6 +1739,7 @@ public final class io/kotest/matchers/nulls/MatchersKt {
public static final fun beNull ()Lio/kotest/matchers/Matcher;
public static final fun shouldBeNull (Ljava/lang/Object;)V
public static final fun shouldNotBeNull (Ljava/lang/Object;)Ljava/lang/Object;
public static final fun shouldNotBeNull (Ljava/lang/Object;Lkotlin/jvm/functions/Function1;)V
}

public final class io/kotest/matchers/optional/MatchersKt {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ fun <T> T?.shouldNotBeNull(): T {
return this!!
}

/**
* Verifies that this is not null and lets you use its value in [block]
*
* maybeNullString() shouldNotBeNull {
* length should beEven()
* }
*/
infix fun <T : Any> T?.shouldNotBeNull(block: T.() -> Unit) {
this.shouldNotBeNull()
block()
}

/**
* Matcher that verifies if a reference is null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ class ShouldNotBeNullTest : WordSpec() {
.shouldStartWith("fo")
.shouldEndWith("oo")
}

"accept a block" {
val a: String? = "foo"

a shouldNotBeNull {
shouldHaveLength(3)
shouldStartWith("fo")
shouldEndWith("oo")
}
}
}
}
}

0 comments on commit 2cd159d

Please sign in to comment.