Thorsten Lorenz edited this page Nov 28, 2010 · 3 revisions

FSharpSpec Expected Exception Assertions

FsharpSpec provides two ways to expect and then inspect thrown exceptions.

In both cases the code raising the exception needs to be wrapped inside a function, so that FSharpSpec can execute it when it is ready to catch the raised exception.

Option 1 - using catch

  1. Catch an exception and store its value in a variable.
  2. Inspect the type of the raised exception and the exceptin message.

Example let thrownException = catch (fun () -> new ArgumentException("Exact Message") |> raise) [ it "thrownException should.be typeof" thrownException should.be typeof it "thrownException.Message should.equal 'Exact Message'" thrownException.Message should.equal "Exact Message" it "thrownException.Message should.contain 'Mess'" thrownException.Message should.contain "Mess" ]

Option 2 - catching and inspecting inline


Allows to make an assertion about the type of an exception

Example it "1/0 should fail with DivideByZeroException" (fun () -> 1 / 0) should.failWith typeof


Allows to test the exact exception message

Example it "failwith 'Exact Message' should.failWith 'Exact Message'" (fun () -> failwith "Exact Message") should.failWithMessage "Exact Message"


Allows to test if the exception message contains a substring

Example it "failwith 'Exact Message' should.failWithMessageContaining 'Mess'" (fun () -> failwith "Exact Message") should.failWithMessageContaining "Mess"


Allows to test if the exception message does not contain a substring

Example it "failwith 'Exact Message' should.failWithMessageNotContaining 'NotContained'" (fun () -> failwith "Exact Message") should.failWithMessageNotContaining "NotContained"