F# Testing with xUnit

I came across a cool tool yesterday for testing F# programs called xUnit and I thought I should give it a try, so here goes.

The first step:  Get it and install it.

The latest version 1.5 is here: http://xunit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28060

Don't worry about any documentation there is none -- you've just got to wing it.  I downloaded the release and unzipped it:

You don't need to do any more that that.

The next thing I did was add a reference to the xunit.dll file:

Now for our first test.  In my last post, I showed how to code a mortgage calculator.  I now want to write a test to prove that it works. 

The first thing I did was I took my present value function (along with my other math functions) and stowed them away in a module called MathMod.

Here is the relevant section of MathMod:

-------------------------------------------------------------

module MathMod

#light
open System
open System.Collections.Generic
open System.IO

let pv (i : float) (n : float) =
     1.0 / Math.Pow( (1.0 + i ), n)

let npv x i n =
    x * (pv i n)

let rec valList aList (ir : float) (n : float) =
    match aList with
    | [] -> []
    | h::t -> npv h ir n :: valList t ir (n+1.0)


let presentValue vals (ir : float) =
    List.fold(+)0.0 <| valList vals ir 0.0

----------------------------------------------------------------------

I next added a new file to my project called "Tests.fs".  I figured I would put all my tests in this file so I could then run them all at once.

Now, the concept behind xUnit is that you

(1) create an .exe or .dll that contains some tests;

(2) compile the .exe or .dll; and then

(3) run an axillary program "Test Runner.exe" that looks in your .exe or .dll for methods that are tagged as tests.  The Test Runner  then runs the tests and notifies you if they have succeeded or failed.  Of course, the Test Runner program is not called that, but rather it is officially named xunit.gui.exe (see above).

So, let's try something simple -- this is what my Test.fs file looks like:

----------------------------------------------------------------------

#light

open System
open System.Collections.Generic
open System.IO
open Xunit
open MathMod


[<Fact>]
let PV_1000() =
     let vals = [-1000.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 1100.0]
     let pv0 = presentValue vals 0.1
     Assert.InRange(pv0,(0.0 - 0.0001),(0.0 + 0.0001))

----------------------------------------------------------------------

Notice, I open Xunit (note the capitalization).  I don't know why xUnit is called Xunit ???

Anyway, a test is structured with a tag  [<Fact>].

You then define a method -- I call it PV_1000() in this example.

Caution:  You must append the open parentheses at the end of the function, otherwise the Test Runner won't identify it as a test.  The program will still compile, it's just that the Test Runner won't find it.  It only took me two friggin' hours to figure this out.

In my test I have a series of numbers whose present value I know should be zero (0.0).  The statement:

Assert.InRange(pv0,(0.0 - 0.0001),(0.0 + 0.0001))

Asserts that the result of the present value calculation (pv0) is in the range of 0 +/- 0.0001.  (I can't use equality here because I am using floating point numbers.)  The Test Runner application will find any method tagged as tag  [<Fact>] and run it.  The Assert statement will be executed and will succeed or fail.

So, let's try it.  I first compile the program in F#.  I then run the Test Runner (xunit.gui.exe).  I then open my assembly:

When I open my assembly, the Test Runner shows the tests it has identified.

To run, the test(s), I just click the run button.

The Test Runner then runs the test and indicates if it has passed or failed:

Here it has passed.

Now here is a test I know will fail:

[<Fact>]
let PV_1000_Fail() =
     let vals = [-1000.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 100.0; 1100.0]
     let pv0 = presentValue vals 0.12
     Assert.InRange(pv0,(0.0-0.0001),(0.0+0.0001))

I have changed the discount rate to 12% which should make the present value less than zero.  I recompile the program and run the Test Runner.

Here's what a failure looks like:

The results screen show the failure and the reason it failed.  Note that the present value is now -113.00 -- this value fails the test.

Cool Huh?

Now, the test I really want to write is a test of my mortgage calculator:

-------------------------------------------------------------

[<Fact>]
let mortgageCalc() =

    let mortgage = 200000.0
    let n = 360
    let i = 0.06

    let ones = List.init n (fun one -> 1.0)

    let pv0 = presentValue ones (i/12.0)

    let levelPayment = mortgage / pv0

    //
    //Now Test
    //
    let payments = List.init n (fun one -> levelPayment)

    let pv2 = presentValue payments (i/12.0)
    Assert.InRange(pv2,(mortgage-0.0001),(mortgage+0.0001))

-------------------------------------------------------------

In this test, I calculate my level payment for a $200,000 mortgage over 360 months at 6.00% interest.  I then calculate create a stream of payments equal to my level payment.  I then discount that stream back to the present.  The result is pv2.  I then Assert that the result pv2 is equal (within a tolerance) of my original mortgage.

I compile and run.

We Pass!

 

Print | posted @ Sunday, July 12, 2009 11:28 AM

Comments on this entry:

Gravatar # Your content is really useful
by dress at 7/15/2010 2:28 AM

and casual dresses on this site
discount Prom dresses
discount wedding dresses
a series of discount Wedding Dresses, Including Wedding gowns, Evening gowns, Wedding Dress, Bridal gowns and Bridal Dress
wedding dresses
prom dresses
  
Gravatar # re: F# Testing with xUnit
by deexu at 7/16/2010 1:39 AM

great range of Ed Hardy products. Ed Hardy Women's Ellerise Lowrise Sneaker · Ed Hardy Women's
ed hardy jeans, ed hardy hoody, ed hardy shirt, ed hardy clothing, ed hardy cap, ed glasses, ed belts,
women fashion shoes, men's clothes. helping .perhaps you will like
Ed Hardy
Ed Hardy shoes
Ed Hardy shirts
Ed Hardy clothes
Ed Hardy clothing
Ed Hardy shoes
Don Ed Hardy is an American tattoo collector raised in Southern California
Ed Hardy Clothing,Christian Audigier,Ed Hardy Shoes,Ed Hardy Swimwear,Ed Hardy Hat,
ED Hardy Caps
Ed Hardy Sunglasses
Ed Hardy Wallets
EdHardy
Gucci outlet store online, numerous cheap Gucci bags, handbags, wallets, purses, totes, shoes on sale,
cheap prices and authentic qualities
gucci handbags
gucci jewelryRGRHUJIO
  
Gravatar # re: F# Testing with xUnit
by Casino Online-Offers at 7/21/2010 3:04 AM

Finally a post that is not about superficial stupid subject. I can't really say about my self regarding my IT knowledge but I'd like to know if the techniques you show us here can be also used in operating online gambling games. Anyhow, a great post and I thank you for it! :)
  
Gravatar # shi
by fiwedding at 7/23/2010 3:15 AM

supply in stock and custom lace front wigs, full lace wigs, lace wigs, human hair wigs,
remy lace front wigs, cheap wigs, cheap, buy, celebrity
full lace wigs
lace wigs
lace wigs sale
lace front wigs
synthetic front lace wigs
A Famous Dresses Shop which sell directly Wedding Dresses, Evening Dress, Bridesmaid Dresses,Prom dresses
cheap wedding dresses
cheap evening dresses
cheap prom dresses
cheap evening dresses
cheap prom dresses
Elegant evening dresses are always associated with the brides and their bridesmaids.Shopping for evening dresses and your wedding dress in stylish bridal..
  
Gravatar # re: F# Testing with xUnit
by ckangel3 at 7/31/2010 12:00 AM

Tiffany Charms
Tiffany Earrings
Tiffany Necklaces

Tiffany jewelry
mous Tiffany Jewelry Shop which sell directly Tiffany Rings, Earrings, Necklaces, Pendants, Bracelets,
Bangles, Accessories.
Tiffany co jewelry
Tiffany
Tiffany Bracelets
affordable tiffany jewelry, beautiful discount tiffany rings, tiffany necklaces,tiffany Pendants,
tiffany earrings and tiffany Bracelets.
Tiffany Charms
Tiffany Earrings
Tiffany Necklaces
Tiffany Rings
Tiffany Jewelry Online,Discount Tiffany & Co Jewelry On Sale,you can buy cheap Tiffany silver.
All jewelry come with Tiffany package
links of london
links london
links of london jewellery

  
Gravatar # re: F# Testing with xUnit
by arek at 8/4/2010 7:34 PM

Perfect for the beach, the gym or just running around town on a warm summer day, Womens Adidas Shoes come in a wide variety of styles and colors that fit many fashions. Properly broken-in and cared-for Mens Adidas Shoes can provide many years of comfort and use.
  
Gravatar # re: F# Testing with xUnit
by designer replica handbag at 8/28/2010 7:26 AM

variety of styles and colors that fit many fashions. ProperlVBvariety of styles and colors that fit many fashions. Properl
  
Gravatar # re: F# Testing with xUnit
by Currency online trading at 8/31/2010 9:58 AM

Thanks for the interesting post
  
Gravatar # re: F# Testing with xUnit
by Trading currency at 8/31/2010 10:00 AM

Nice post man :)
  
Gravatar # <A href="http://www.timberland4you.co.uk/">timberland shoe company</A>
by timberland for you at 9/1/2010 8:11 PM

On a certain cheap timberland boots day at a certain hour, we will pull into the station. Bands will be playing and flags discount timberland boots waving. Once we get there, so many wonderful timberland winter boots dreams will come true and the pieces of our lives will fit together like a completed jigsaw puzzle. How restlessly we pace the aisles, womens timberland boot the minutes for loitering --waiting, waiting, waiting for the station.But uppermost in our timberland shoes store minds is the final destination. On a certain day at a certain hour, we will pull into the station. Bands will be playing and timberland eye boat flags waving. Tucked away in our timberland for you subconscious is an idyllic vision. We see ourselves on a long trip that timberland 6 inch spans the continent. We are traveling by train. Out timberland hiking boots windows, we drink in the passing scene of cars on nearby highways, of children timberland shoe company waving at a crossing, of cattle grazing on a distant timberland boots hillside, of smoke pouring from a power plant, of row upon row of corn and wheat, of flatlands and timberland wheat shoes valleys, of mountains and rolling classic 3 eye timberland boat hillsides, of city skylines and village halls.But uppermost in our black timberland boots minds is the final destination.
  
Gravatar # re: F# Testing with xUnit
by nannan at 9/2/2010 11:11 PM

Tiffany jewellery
Tiffany
variety of styles and colors that fit many fashions. ProperlVBvariety of styles and colors that fit many fashions. Properl
Tiffany & Co
Tiffany Co Bracelets
Tiffany Co Charms
Tiffany Co Earrings
Tiffany sale
Tiffany Co Necklaces
Tiffany uk
Tiffany Co Rings
tiffany jewelry
tiffany co
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 4 and type the answer here: