visual studio 2012 - For unit tests written in F# with mstest in vs2012, how do I assert that an exception is raised? -
i'm writing unit tests in f# using mstest, , i'd write tests assert exception raised. 2 methods can find doing either (1) write tests in c# or (2) don't use mstest, or add test package, xunit, on top of it. neither of these option me. thing can find on in msdn docs, omits f# examples.
using f# , mstest, how assert particular call raises particular exception?
mstest has expectedexceptionattribute
can used, less ideal way test exception has been thrown because doesn't let assert specific call should throw. if method in test method throws expected exception type, test passes. can bad commonly used exception types invalidoperationexception
. use mstest lot , have throws
helper method in our own asserthelper
class (in c#). f# let put assert
module appears other assert methods in intellisense, pretty cool:
namespace fsharptestspike open system open microsoft.visualstudio.testtools.unittesting module assert = let throws<'a> f = let mutable wasthrown = false try f() | ex -> assert.areequal(ex.gettype(), typedefof<'a>, (sprintf "actual exception: %a" ex)); wasthrown <- true assert.istrue(wasthrown, "no exception thrown") [<testclass>] type mytestclass() = [<testmethod>] member this.``expects exception , thrown``() = assert.throws<invalidoperationexception> (fun () -> invalidoperationexception() |> raise) [<testmethod>] member this.``expects exception , not thrown``() = assert.throws<invalidoperationexception> (fun () -> ()) [<testmethod>] member this.``expects invalidoperationexception , different 1 thrown``() = assert.throws<invalidoperationexception> (fun () -> exception("boom!") |> raise)
Comments
Post a Comment