How do I write an async unit test method in F#

Viewed 829

How do I write an async test method in F#?

I'm referencing the following code:

[TestMethod]
public async Task CorrectlyFailingTest()
{
  await SystemUnderTest.FailAsync();
}

This is my failed attempt:

[<Test>]
let ``Correctly failing test``() = async {

        SystemUnderTest.FailAsync() | Async.RunSynchronously
    }
4 Answers

I asked https://github.com/fsprojects/FsUnit/issues/153 because I think that it is a responsibility of the F# unit testing framework to provide a right binding. Meanwhile, this looks the best for me.

    open System.Threading.Tasks

    let runAsyncTest async = async |> Async.StartImmediateAsTask :> Task

    [<Test>]
    let ``Some test`` () = runAsyncTest <| async {
    }

This is an old question but now can use the task builder from the Ply package for testing C# async methods in Xunit like so:

    open FSharp.Control.Tasks
    open System.Threading
    open Xunit
    
    let ``Test some Task returning async method`` () =
        task {
            let! actual = MyType.GetSomethingAsync()
            Assert.Equal(expected, actual)
            
            return ()
        }
Related