Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
like image 312
Scott Nimrod Avatar asked Sep 14 '17 20:09

Scott Nimrod


1 Answers

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.

like image 89
Terrance Avatar answered Oct 06 '22 01:10

Terrance