2
votes

Here is a toy example:

I have a method last[T](ts: Seq[T]): Try[T] which returns either:

  • the last element of a non-empty list wrapped in a Success, or
  • a NoSuchElementException wrapped in a Failure.

I have been reading the scalatest doc pertaining to TryValues and came up with the following scalatest:

"The solution" should "Find the last element of a non-empty list" in {
      last(Seq(1, 1, 2, 3, 5, 8)).success.value should equal (8)
      // ...
    }

  it should "Fail with NoSuchElementException on an empty list" in {
    // Option 1: what I would like to do but is not working
    last(Nil).failure.exception should be a[NoSuchElementException]

    // Option 2: is working but actually throws the Exception, and does not test explicitly test if was in a Failure
    a [NoSuchElementException] should be thrownBy {last(Nil).get}
} 

Is there a way to make my option 1 work?

1

1 Answers

7
votes

You should use shouldBe word to assert type, like:

test.failure.exception shouldBe a [NoSuchElementException]

for type not equal, like:

test.failure.exception should not be an [NoSuchElementException]

See more: http://www.scalatest.org/user_guide/using_matchers