Search code examples
f#xunit

Cannot test for exceptions in F# using xUnit


Here is the code:

module Tests

open System
open Xunit

[<Fact>]
let ``Simple Test`` () =
    Assert.Throws<Exception>(failwith "Error")
        

This fails to compile with:

error FS0041: A unique overload for method 'Throws' could not be determined based on type information prior to this program point. A type annotation may be needed. Known type of argument: 'a  Candidates: - Assert.Throws<'T when 'T :> exn>(testCode: Action) : 'T - Assert.Throws<'T when 'T :> exn>(testCode: Func<Threading.Tasks.Task>) : 'T - Assert.Throws<'T when 'T :> exn>(testCode: Func<obj>) : 'T

What am I doing wrong?


Solution

  • Its looking for an Action or a Func, you CAN use a F# lambda and the compiler will implicitly create a Func for you.

    module Tests
    
    open System
    open Xunit
    
    [<Fact>]
    let ``My test`` () =
        Assert.Throws<Exception>(
            fun () -> 
                (failwith "Error") :> obj)
    

    you have to cast the output in this example to tell compiler what the return type of the function is (it could be anything, as it returns nothing)