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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With