From 9eb4b57086b129213cb69dc8c964dde84532a266 Mon Sep 17 00:00:00 2001 From: rcardin Date: Wed, 10 Apr 2024 11:26:46 +0200 Subject: [PATCH] Added tests for the 'recover' function --- src/main/scala/in/rcard/raise4s/Raise.scala | 2 +- .../scala/in/rcard/raise4s/RaiseSpec.scala | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/scala/in/rcard/raise4s/Raise.scala b/src/main/scala/in/rcard/raise4s/Raise.scala index bb2da5b..efff27b 100644 --- a/src/main/scala/in/rcard/raise4s/Raise.scala +++ b/src/main/scala/in/rcard/raise4s/Raise.scala @@ -31,5 +31,5 @@ def ensureNotNull[B, Error](value: B, raise: () => Error)(using r: Raise[Error]) * @return * The result of the block or the fallback value */ -def recover[Error, A](block: Raise[Error] ?=> () => A)(recover: Error => A): A = +def recover[Error, A](block: Raise[Error] ?=> () => A, recover: Error => A): A = fold(block, ex => throw ex, recover, identity) diff --git a/src/test/scala/in/rcard/raise4s/RaiseSpec.scala b/src/test/scala/in/rcard/raise4s/RaiseSpec.scala index ee10e6a..b21d584 100644 --- a/src/test/scala/in/rcard/raise4s/RaiseSpec.scala +++ b/src/test/scala/in/rcard/raise4s/RaiseSpec.scala @@ -40,4 +40,31 @@ class RaiseSpec extends AnyFlatSpec with Matchers { ) actual should be(43) } + + "recover" should "return the value if it is not an error" in { + val actual = recover( + () => 42, + error => 43 + ) + + actual should be(42) + } + + it should "return the recovery value if the value is an error" in { + val actual = recover( + () => raise("error"), + error => 43 + ) + + actual should be(43) + } + + it should "rethrow the exception" in { + assertThrows[RuntimeException] { + recover( + () => throw new RuntimeException("error"), + error => 43 + ) + } + } }