Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MSTest has an <code>ExpectedExceptionAttribute</code> that can be used, but it is a less than ideal way to test an exception has been thrown because it doesn't let you assert the specific call that should throw. If any method in the test method throws the expected exception type, then the test passes. This can be bad with commonly used exception types like <code>InvalidOperationException</code>. I use MSTest a lot and we have a <code>Throws</code> helper method for this in our own <code>AssertHelper</code> class (in C#). F# will let you put it into an <code>Assert</code> module so that it appears with all the other Assert methods in intellisense, which is pretty cool:</p> <pre><code>namespace FSharpTestSpike open System open Microsoft.VisualStudio.TestTools.UnitTesting module Assert = let Throws&lt;'a&gt; f = let mutable wasThrown = false try f() with | ex -&gt; Assert.AreEqual(ex.GetType(), typedefof&lt;'a&gt;, (sprintf "Actual Exception: %A" ex)); wasThrown &lt;- true Assert.IsTrue(wasThrown, "No exception thrown") [&lt;TestClass&gt;] type MyTestClass() = [&lt;TestMethod&gt;] member this.``Expects an exception and thrown``() = Assert.Throws&lt;InvalidOperationException&gt; (fun () -&gt; InvalidOperationException() |&gt; raise) [&lt;TestMethod&gt;] member this.``Expects an exception and not thrown``() = Assert.Throws&lt;InvalidOperationException&gt; (fun () -&gt; ()) [&lt;TestMethod&gt;] member this.``Expects an InvalidOperationException and a different one is thrown``() = Assert.Throws&lt;InvalidOperationException&gt; (fun () -&gt; Exception("BOOM!") |&gt; raise) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload