Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading