Skip to content

Instantly share code, notes, and snippets.

@arturopala
Last active April 27, 2020 07:17
Show Gist options
  • Save arturopala/4cfd20de97006031329a946f08c54f20 to your computer and use it in GitHub Desktop.
Save arturopala/4cfd20de97006031329a946f08c54f20 to your computer and use it in GitHub Desktop.
Scala trait adding ScalaTest's AnyWordSpec compatibility to MUnit
import scala.reflect.ClassTag
trait AnyWordSpecCompat extends munit.FunSuite {
implicit class NameExt[T](name: String) {
def in(body: => T): Unit = test(name)(body)
def should(body: => T): Unit = {
val pos0 = munitTestsBuffer.length
body
val pos1 = munitTestsBuffer.length
for (i <- pos0 until pos1) {
munitTestsBuffer(i) = {
val test = munitTestsBuffer(i)
test.withName(name + " should " + test.name)
}
}
}
}
implicit class IterableExt[T](iterable: Iterable[T]) {
def shouldBe(expected: Iterable[T])(implicit loc: munit.Location): Unit = {
assert(iterable.size == expected.size, "both collections must have the same size")
iterable.zip(expected).foreach { case (a, b) => assertEquals(a, b) }
}
}
implicit class ValueExt[T](value: T) {
def shouldBe(expected: T)(implicit loc: munit.Location): Unit =
assertEquals(value, expected)
def should(word: not.type): NotWord[T] = NotWord(value)
}
case object not
case object thrownBy {
def apply[T](body: => T): ThrownByWord[T] = ThrownByWord(() => body)
}
case class NotWord[T](value: T) {
def be(expected: T)(implicit loc: munit.Location): Unit =
assertNotEquals(value, expected)
}
def an[E <: Throwable: ClassTag]: AnWord[E] = new AnWord[E]
class AnWord[E <: Throwable: ClassTag] {
def shouldBe[T](thrownBy: ThrownByWord[T]): Unit =
intercept[E](thrownBy.body())
}
case class ThrownByWord[T](body: () => T)
}
class Test extends AnyWordSpecCompat {
"MyTest" should {
"use ScalaTest matchers" in {
(1 + 1) shouldBe 2
(1 + 1) should not be 3
Option(1 + 1) shouldBe Some(2)
(0 until 10) shouldBe List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
an[NotImplementedError] shouldBe thrownBy(???)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment