通常我在 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 http://xunit.github.io/docs/capturing-output.html)需要编写一个构造函数,它接受一个ITest输出助手然后使用它代替 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);
}
}
然而 fsharp 模块是静态类,测试是静态方法。没有构造函数来注入输出助手。
有没有办法访问当前测试的当前输出助手。我知道我可以将 fsharp 测试重写为非静态类,但这是不希望的。
查看XUnit源码后。
https://github.com/xunit/xunit/blob/e64f566b75f93cd3cec27f950759d82832bfe44b/src/xunit.execution/Sdk/Frameworks/Runners/TestClassRunner.cs#L90 https://github.com/xunit/xunit/blob/e64f566b75f93cd3cec27f950759d82832bfe44b/src/xunit.execution/Sdk/Frameworks/Runners/TestClassRunner.cs#L90
我很确定这是一个被忽视的案例。没有将助手注入到静态类中。
如果 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 @>
如果 xUnit 支持一些其他选项,那就太好了 - 我怀疑他们可能会接受建议,如果它不会太尴尬(也许使用方法参数?)
但除非 xUnit 添加对其他方法的支持,否则我认为您需要将 F# 对象与方法一起使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)