How to capture results with XUnit 2.0 and FSharp style tests

I usually write my unit tests in F # as

open Swensen.Unquote open Xunit module MyTests = [<Fact>] let ``SomeFunction should return 10`` () = let a = SomeFunction() test <@ a = 10 @> [<Fact>] let ``SomeOtherFunction should return 11`` () = let a = SomeFunction() test <@ a = 11 @> 

If I want to log into the console from xunit (according to http://xunit.imtqy.com/docs/capturing-output.html ), I need to write a constructor that accepts ITestOutputHelper , and then use this instead of Console.WriteLine and the family.

 using Xunit; using Xunit.Abstractions; public class MyTestClass { private readonly ITestOutputHelper output; public MyTestClass(ITestOutputHelper output) { this.output = output; } [Fact] public void MyTest() { var temp = "my class!"; output.WriteLine("This is output from {0}", temp); } } 

however, fsharp modules are static classes, and tests are static. There is no constructor to enter the output helper.

Is there a way to access the current output helper for the current test. I know that I could rewrite my fsharp tests as non-static classes, but this is not desirable.

After viewing the XUnit source.

https://github.com/xunit/xunit/blob/e64f566b75f93cd3cec27f950759d82832bfe44b/src/xunit.execution/Sdk/Frameworks/Runners/TestClassRunner.cs#L90

I am sure this is a missed case. The helper gets up in static classes.

+8
f # xunit
source share
1 answer

If xUnit does not have an alternative mechanism for entering parameters, then, I think, the only option is to define tests as methods in the F # object type. I also prefer to write tests as functions with let , but the following simple object type doesn’t look so bad:

 open Swensen.Unquote open Xunit open Xunit.Abstractions type MyTests(output:ITestOutputHelper) = [<Fact>] member __.``SomeFunction should return 10`` () = let a = SomeFunction() output.WriteLine("Some function returned {0}", a) test <@ a = 10 @> 

It would be nice if xUnit supported some other option for this - I suspect they might be open to suggestions if this is something not too inconvenient (perhaps using a method parameter?)

But if xUnit adds support for some other method, I think you will need to use an F # object with methods.

+8
source share

All Articles