如何使用XUnit 2.0和FSharp样式测试捕获输出

bra*_*ing 12 f# xunit

通常我用F#编写单元测试

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 @>
Run Code Online (Sandbox Code Playgroud)

如果我希望从xunit登录到控制台(根据http://xunit.github.io/docs/capturing-output.html),则需要编写一个构造函数,该构造函数接受ITestOutputHelper然后使用它而不是Console.WriteLine和家人.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是fsharp模块是静态类,测试是静态方法.没有构造函数来注入输出帮助器.

有没有办法访问当前测试的当前输出助手.我知道我可以将我的fsharp测试重写为非静态类,但这是不受欢迎的.

看完XUnit源代码之后.

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

我很确定这是一个被忽视的案例.没有将辅助函数注入静态类.

Tom*_*cek 13

如果xUnit没有任何替代注入参数的机制,那么我想唯一的选择是将测试定义为F#对象类型中的方法.我也更喜欢将测试编写为函数使用let,但下面的简单对象类型看起来并不太糟糕:

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 @>
Run Code Online (Sandbox Code Playgroud)

如果xUnit支持其他一些选项会很好 - 我怀疑他们可能会接受建议,如果它不是太尴尬(可能使用方法参数?)

但除非xUnit添加了对其他方法的支持,否则我认为你需要在方法中使用F#对象.

  • 我在 VS Code 中仍然没有得到任何输出。 (2认同)