1/* 2 * Copyright 2001-2009 Artima, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package org.scalatest.matchers 17 18import org.scalatest._ 19 20class ShouldThrowSpec extends WordSpec with ShouldMatchers { 21 22 "The evaluating { ... } should produce [ExceptionType] syntax" should { 23 24 "fail if a different exception is thrown" in { 25 val caught1 = intercept[TestFailedException] { 26 evaluating { "hi".charAt(-1) } should produce [IllegalArgumentException] 27 } 28 assert(caught1.getMessage === "Expected exception java.lang.IllegalArgumentException to be thrown, but java.lang.StringIndexOutOfBoundsException was thrown.") 29 } 30 31 "fail if no exception is thrown" in { 32 val caught2 = intercept[TestFailedException] { 33 evaluating { "hi" } should produce [IllegalArgumentException] 34 } 35 assert(caught2.getMessage === "Expected exception java.lang.IllegalArgumentException to be thrown, but no exception was thrown.") 36 } 37 38 "succeed if the expected exception is thrown" in { 39 evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException] 40 } 41 42 "succeed if a subtype of the expected exception is thrown, where the expected type is a class" in { 43 evaluating { "hi".charAt(-1) } should produce [Exception] 44 } 45 46 "succeed if a subtype of the expected exception is thrown, where the expected type is a trait" in { 47 trait Excitement 48 def kaboom() { throw new Exception with Excitement } 49 evaluating { kaboom() } should produce [Excitement] 50 } 51 52 "return the caught exception" in { 53 def kaboom() { throw new Exception("howdy") } 54 val thrown = evaluating { kaboom() } should produce [Exception] 55 thrown.getMessage should be === "howdy" 56 } 57 } 58} 59