通常我用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源代码之后.
我很确定这是一个被忽视的案例.没有将辅助函数注入静态类.
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#对象.