I’m trying to write some NUnit tests in F# and having trouble passing a function to the ThrowsConstraint. A distilled (non)working sample is below.
open System.IO
open NUnit.Framework
[<TestFixture>]
module Example =
[<Test>]
let foo() =
let f = fun () -> File.GetAttributes("non-existing.file")
Assert.That(f, Throws.TypeOf<FileNotFoundException>())
This compiles just fine but I get the following from the NUnit test runner:
FsTest.Tests.Example.foo:
System.ArgumentException : The actual value must be a TestDelegate but was f@11
Parameter name: actual
While I’m able to work around the problem using ExpectedException attribute, my question is what is the correct way of using an F# function in this situation?
All you need to do in order for your original snippet to work is fixing
fto have signature conformant toTestDelegate, which isunit -> unit. Just discard return value ofFile.GetAttributes:F# compiler did not barf at your original code because just another fitting NUnit overload
Assert.That(actual: obj, expression: Constraints.IResolveConstraint)exists.As
Assert.Thathas very broad usage I’d stick for testing expected exceptions to more specific assert form, for example:where F# compiler would be able statically spot the wrong signature of your function.