Search code examples
f#mstestc#-to-f#

In F#, how does one access the TestContext for .runsettings?


I'm writing an integration test for a third party C# library in an F# code base. There are some constraints to this integration test.

  • For regulatory reasons I must test with MsTest
  • The library only works with a valid license
  • We cannot commit the license into our repository
  • I don't want to hardcode the location of the valid license into the test

I've got the failing test passing, but can't figure out how to write the test with a valid license. The function Initialize is just a wrapper for the third party library to initialize the library with the license and returns the Result.

[<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")

The test I want to write is "given a valid license file, initializing the library should return a Result of OK."

In C#, I would use the .runsettings to point to a license folder, but I'm pretty new to F# and I'm not really sure how I would add the TestContext to the test. Since the tests are defined as a type, I'm guessing they don't hold state or fields.

So my questions are:

  • Is there a way to load the TextContext in F#?
  • Is there a more idiomatic way to achieve this in F#?

Solution

  • It works much the same as in C#. In your test class, mark a static member with the ClassInitialize or AssemblyInitialize attribute and specify a context parameter:

    [<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)