How to intentionally throw and catch an exception with ScalaTest

If you ever need to intentionally throw and catch an exception with ScalaTest, here’s an example of how to do that:

test("verify splitCamelCase throws a NPE when given a null") {
    val e: NullPointerException = intercept[NullPointerException] {
        val s = splitCamelCase(null)
    }
    assert(e.isInstanceOf[NullPointerException])
}

In this test I want to make it clear that I expect that if you give the splitCamelCase method a null value, it will throw a null pointer exception (NullPointerException).

As shown, the ScalaTest intercept method is the key to this solution. It lets you “intercept” (handle) the exception that’s thrown by splitCamelCase and then assign it to a variable. Then I can test that exception variable in the assert method. I show a NullPointerException here but the same technique should work with any Throwable type.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.