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

时间:2015-08-12 14:22:23

标签: 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 @>

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

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

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

查看XUnit源代码。

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

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

1 个答案:

答案 0 :(得分:11)

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

    String hint = chatText.getText().toString();
    String text = "hi+";
    Boolean found;
    found = text.contains(hint);

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

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