Saturday, December 20, 2008

Object Mocking in F# with Rhino Mocks

Near the end of Oct. 2008, I posted an entry entitled Mocking F#.  While that post may be helpful to some, others may be looking for an example of how to dynamically mock objects from tests written in F#.  This post will attempt to provide that example.  In addition, it will provide another example of a BDD approach using some of the functionality in SpecUnit (a previous example is here).

Since the types being tested have not changed from those provided in the Mocking F# post, I will not be re-posting them here. 

#light
namespace FSharpMockExample.Services.Specs
open FSharpMockExample.Services
open FSharpMockExample.Entities
open FSharpMockExample.Data
open NUnit.Framework
open SpecUnit
open Rhino.Mocks

[<TestFixture>]
[<Concern("Customer Balance Calculation")>]
type behaves_like_context_with_customer_balance_calculation() = 
    inherit ContextSpecification()
    [<DefaultValue(false)>]
    val mutable customerService : ICustomerService
    [<DefaultValue(false)>]
    val mutable mocks : MockRepository
    override this.Context () = 
        this.mocks <- new MockRepository()
        ignore None

[<TestFixture>]
[<Concern("Customer Balance Calculation")>]
type When_calculating_balance_with_starting_balance_of_fifty_and_ten_percent_discount() = 
    inherit behaves_like_context_with_customer_balance_calculation()
    override this.Because () = 
        this.mocks <- new MockRepository()
        let cAgs = [||]
        let customerDao = this.mocks.DynamicMock<ICustomerDao>(cAgs)
        let customer = new Customer(1, "XYZ Company", 50.00M)
        Expect.Call(customerDao.GetById(1)).Return(customer) |> ignore
        this.customerService <- new CustomerService(customerDao) 
    [<Observation>]
    member this.should_have_a_calculated_balance_of_forty_five() = 
        this.mocks.ReplayAll();
        this.customerService.CalculateBalaceWithDiscount(1, 0.1M).ShouldEqual(45M) |> ignore
        this.mocks.VerifyAll();


0 comments: