How to pass NUnit Throw Constraint function?

I am trying to write some NUnit tests in F # and a problem with passing a function to ThrowsConstraint . Below is a distilled (non) working sample.

 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 can work around the problem using the ExpectedException attribute, my question is, what is the correct way to use the F # function in this situation?

+6
source share
2 answers

All you need to do to get your source snippet to work is fixing f so that the signature matches TestDelegate , which is unit -> unit . Just File.GetAttributes return value of File.GetAttributes :

 let f = fun () -> File.GetAttributes("non-existing.file") |> ignore 

The F # compiler did not run your source code because there is only one installation of NUnit overload Assert.That(actual: obj, expression: Constraints.IResolveConstraint) .

Since Assert.That is very widely used, I would stick with a more specific statement form for checking expected exceptions, for example:

 [<Test>] let foo() = Assert.Throws<FileNotFoundException> (fun () -> File.GetAttributes("non-existing.file")|> ignore) |> ignore 

where the F # compiler could statically determine the incorrect signature of your function.

+7
source

IMHO, you can save some pain by using Unquote on top of NUnit. Then your statement will be as simple as

 [<Test>] let foo() = raises<FileNotFoundException> <@ File.GetAttributes("non-existing.file") @> 

NUnit is a large set of overloads with assertions with sometimes unexpected runtime behavior designed to compensate for the relative lack of C # relative to expressiveness compared to F #.

At the same time, since F # already has features such as structural comparison for elegantly expressing statements, Unquote is designed to use its own functions with only three simple statement statements: test , raises , and raisesWith .

+4
source

All Articles