How do I write an async unit test method in F#
So after a bit of research, it turns out that this is more difficult than it ought to be. https://github.com/nunit/nunit/issues/34
That being said a workaround was mentioned. This seems kinda lame but, it looks like declaring a task delegate outside as a member and leveraging it is a viable work around.
The examples mentioned in the thread:
open System.Threading.Tasks
open System.Runtime.CompilerServices
let toTask computation : Task = Async.StartAsTask computation :> _
[<Test>]
[<AsyncStateMachine(typeof<Task>)>]
member x.``Test``() = toTask <| async {
do! asyncStuff()
}
And
open System.Threading.Tasks
open NUnit.Framework
let toAsyncTestDelegate computation =
new AsyncTestDelegate(fun () -> Async.StartAsTask computation :> Task)
[<Test>]
member x.``TestWithNUnit``() =
Assert.ThrowsAsync<InvalidOperationException>(asyncStuff 123 |> toAsyncTestDelegate)
|> ignore
[<Test>]
member x.``TestWithFsUnit``() =
asyncStuff 123
|> toAsyncTestDelegate
|> should throw typeof<InvalidOperationException>
XUnit had a similar problem and did come up with a solution: https://github.com/xunit/xunit/issues/955
So you should be able to do this in xunit
[<Fact>]
let ``my async test``() =
async {
let! x = someAsyncCall()
AssertOnX
}
Sorry if this is not the most satisfying answer.
open Xunit
[<Fact>]
let ``my async test``() =
async {
do! Async.AwaitTask(someAsyncCall())|> Async.Ignore
AssertOnX
}