Search code examples
f#nunitfsunit

How to use NUnit with F# properly?


I have stucked with the unit testing. I have the following source code:

module SampleTest
open FsUnit

open NUnit.Framework

[<TestFixture>]
[<Category("Category name")>]
type DoSthTest() =

    let mutable state = []

    [<SetUp>]
    member public x.``run before test``() =
        state = []

    [<Test>]
    member x.``add item``() =
        state <- List.append state [1]
        state.Length |> should equal 1

In general it runs fine.... but without the [] function. I got the following exception: Result Message: Invalid signature for SetUp or TearDown method: run before test

Does someone know the answer why ? And the second question is: is it possible to write an unittest without type definition but with the SetUp also function working? I mean sth like this:

module SampleTest

open FsUnit
open NUnit.Framework


let mutable state = []

[<SetUp>]
let ``run before test``() =
    state = []

[<Test>]
let ``add item``() =
    state <- List.append state [1]
    state.Length |> should equal 1

again I got the same exception as before


Solution

  • In F#, mutable values are assigned using <- rather than =.

    So your Setup method should look like:

    [<SetUp>]
    member public x.``run before test``() =
        state <- []
    

    which works fine.

    For your second question, this layout works fine for me if you make the same change as above.