From 834e29ff7f2047054e4af4c05311943bcbe480a7 Mon Sep 17 00:00:00 2001 From: Den Shabalin Date: Fri, 9 Aug 2013 15:36:26 +0200 Subject: add assertThrows testing utility function This is much easier to use than built-in JUnit method-level checks. --- .../scala/tools/testing/AssertThrowsTest.scala | 25 ++++++++++++++++++++++ test/junit/scala/tools/testing/AssertUtil.scala | 19 ++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 test/junit/scala/tools/testing/AssertThrowsTest.scala create mode 100644 test/junit/scala/tools/testing/AssertUtil.scala (limited to 'test') diff --git a/test/junit/scala/tools/testing/AssertThrowsTest.scala b/test/junit/scala/tools/testing/AssertThrowsTest.scala new file mode 100644 index 0000000000..ecc46244bd --- /dev/null +++ b/test/junit/scala/tools/testing/AssertThrowsTest.scala @@ -0,0 +1,25 @@ +package scala.tools +package testing + +import org.junit.Assert._ +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import AssertUtil.assertThrows + +@RunWith(classOf[JUnit4]) +class AssertThrowsTest { + class Foo extends Exception + class Bar extends Exception + + @Test + def catchFoo = assertThrows[Foo] { throw new Foo } + + @Test + def rethrowBar = + try assertThrows[Foo] { throw new Bar } + catch { + case bar: Bar => + case e: Throwable => fail(s"expected Bar but got $e") + } +} \ No newline at end of file diff --git a/test/junit/scala/tools/testing/AssertUtil.scala b/test/junit/scala/tools/testing/AssertUtil.scala new file mode 100644 index 0000000000..9efa9327a7 --- /dev/null +++ b/test/junit/scala/tools/testing/AssertUtil.scala @@ -0,0 +1,19 @@ +package scala.tools +package testing + +/** This module contains additional higher-level assert statements + * that are ultimately based on junit.Assert primitives. + */ +object AssertUtil { + /** Check if exception T was thrawn during evaluation of f. If any + * other exception or throwable is found instead it will be re-thrown. + */ + def assertThrows[T <: Exception](f: => Any)(implicit manifest: Manifest[T]): Unit = + try f + catch { + case e: Exception => + val clazz = manifest.erasure.asInstanceOf[Class[T]] + if (!clazz.isAssignableFrom(e.getClass)) + throw e + } +} \ No newline at end of file -- cgit v1.2.3