问题描述
我正在为 F# 代码库中的第三方 C# 库编写集成测试。此集成测试存在一些限制。
- 出于监管原因,我必须使用 MsTest 进行测试
- 该库仅适用于有效许可
- 我们无法将许可证提交到我们的存储库中
- 我不想将有效许可证的位置硬编码到测试中
我通过了失败的测试,但不知道如何使用有效的许可证编写测试。函数 Initialize
只是第三方库的包装器,用于使用许可初始化库并返回结果。
[<TestClass>]
type ``Test Local Initialize`` () =
[<TestMethod>]
member this.``When loading an invalid INI file`` () =
let actual =
$@"{AppDomain.CurrentDomain.BaseDirectory}Resources\DummyLicense.INI"
|> Initialize
match actual with
| Ok _ -> Assert.Fail("Should not initialize with an invalid configuration.")
| Error e -> Assert.IsNotNull(e,"Should error with an invalid configuration")
我想写的测试是“给定一个有效的许可文件,初始化库应该返回 OK 的结果。”
在 C# 中,我会使用 .runsettings
指向许可证文件夹,但我对 F# 还很陌生,我不确定如何将 TestContext
添加到测试中.由于测试被定义为 type
,我猜它们不包含状态或字段。
所以我的问题是:
- 有没有办法在 F# 中加载
TextContext
? - 在 F# 中是否有更惯用的方法来实现这一点?
解决方法
它的工作方式与 C# 中的非常相似。在您的测试类中,使用 ClassInitialize
或 AssemblyInitialize
属性标记静态成员并指定上下文参数:
[<TestClass>]
type TestClass () =
static let mutable myValue = ""
[<ClassInitialize>]
static member Setup(context : TestContext) =
myValue <- string context.Properties.["MyValue"]
[<TestMethod>]
member this.TestMyValue() =
Assert.AreEqual("xyzzy",myValue)