Tuesday, January 15, 2008

Sample setup for Visual Studio 2008 for F# Unit Testing with NUnit

Here is an example of how I configured a vs2008 solution for building a small F# application using Test Driven Development (TDD) techniques and NUnit. I thought I’d share. Here’s the directory structure layout: C:\Projects\F#Projects\myApp · contains the sln file C:\Projects\F#Projects\myApp\myApp · contains the “production” fs files and fsharp project files C:\Projects\F#Projects\myApp\myApp_Tests · contains the test fs files and fsharp project files C:\Projects\F#Projects\myApp\Output · has a copy of nunit.framework.dll I started with a new F# solution and added two projects, myApp and myApp_Tests, both projects have their output paths set to the output directory. The myApp project I configured to be an exe and the myApp_Tests project I configured it to be a dll. (What the myApp project is compiled to really doesn’t matter, it all depends on your final use.) There’s a few additional configuration tasks I had to setup before I could start coding. In the myApp project I qualified it with module myApp so my code and tests could be in separate files. In the myApp_Tests project, I updated the DLL references section with these two entries: -r "C:\Projects\F#Projects\myApp\Output\Nunit.framework.dll" -r "C:\Projects\F#Projects\myApp\Output\myapp.exe" If you don’t want to update the dll references properties, you can add the references in your fs file as listed below. #r @"..\Output\nunit.framework.dll" #r @"..\Output\myapp.exe" I also had to set a project dependancy order to build myApp first then myApp_Tests second, via the solution properties menu. Whew, at last I can new write some code! (The formatting is a little off due to the encoding.) Here’s the myApp_Tests.fs file:
#light open NUnit.Framework [<TestFixture>] type myAppTests = class new() = {} [<Test>] member t.ShouldReturn2() = Assert.AreEqual(2,myApp.AddTwoNumbers(1,1)) [<test>] member t.ShouldReturn45() = Assert.AreEqual(45,myApp.AddTwoNumbers(13,32)) end
Here’s the myApp.fs file:
#light module myApp let AddTwoNumbers a b = a + b
Once you build your solution you can open Nunit Gui, find your test assembly and run your tests untill your in the green! (Make sure you enable NUNit’s shadow copy, so you can keep you project and Nunit open at the same time.) When you add a test, go back to NUnit and re-run, your new test will automatically show up. Feeback and comments are welcome! Enjoy!

3 comments:

DevHawk said...

You should check out xUnit.net for unit testing in F#. It supports static test methods, so you can write test functions directly w/o needing to put them inside a class. I described it on my blog @ Practical F# Parsing: Unit Testing.

Nate Hoellein said...

Thanks! I'll check out xUnit

Ben Hall said...

Interesting post.

I wrote a intro to XUnit last week

http://blog.benhall.me.uk/2008/01/introduction-to-xunit.html