SlideShare a Scribd company logo
1 of 32
Unit Testing with Foq
@ptrelford on @c4fsharp March 2013
Go download on Nuget or foq.codeplex.com
Testing Language
what should a language for writing
                 acceptance tests be?




A Language for Testing
Tests operate by example
                 they describe specific
              scenarios and responses




A Language for Testing
I wonder if a different kind of
               programming language
                           is required.
                          - Martin Fowler 2003




A Language for Testing
UNIT TESTING WITH F#
F# as a Testing Language
F# NUnit                                    C# NUnit
module MathTest =                           using NUnit.Framework;

open NUnit.Framework                        [TestFixture]
                                            public class MathTest
                                            {
let [<Test>] ``2 + 2 should equal 4``() =
                                                [Test]
    Assert.AreEqual(2 + 2, 4)                   public void
                                                    TwoPlusTwoShouldEqualFour()
                                                {
                                                    Assert.AreEqual(2 + 2, 4);
                                                }
                                            }




NUnit
let [<Test>] ``2 + 2 should equal 4``() =
    2 + 2 |> should equal 4




FsUnit
let [<Test>] ``2 + 2 should equal 4``() =
    test <@ 2 + 2 = 4 @>




Unquote
.NET MOCKING
F# as a Testing Language
Mocking libraries
unittesting
var mock = new Mock<ILoveThisFramework>();

// WOW! No record/replay weirdness?! :)
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
   .Returns(true)
   .AtMostOnce();

// Hand mock.Object as a collaborator and exercise it,
// like calling methods on it...
ILoveThisFramework lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");

// Verify that the given method was indeed called with the expected
value
mock.Verify(framework => framework.DownloadExists("2.0.0.0"));




Moq
// Creating a fake object is just dead easy!
// No mocks, no stubs, everything's a fake!
var lollipop = A.Fake<ICandy>();
var shop = A.Fake<ICandyShop>();

// To set up a call to return a value is also simple:
A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop);

// Use your fake as you would an actual instance of the faked type.
var developer = new SweetTooth();
developer.BuyTastiestCandy(shop);

// Asserting uses the exact same syntax as when configuring calls,
// no need to teach yourself another syntax.
A.CallTo(() => shop.BuyCandy(lollipop)).MustHaveHappened();




FakeItEasy
Mock object                               Object Expression
Mock<IShopDataAccess>()                   { new IShopDataAccess with
 .Setup(fun data ->                         member __.GetProductPrice(productId) =
 <@ data.GetProductPrice(any()) @>)           match productId with
   .Calls<int>(function                       | 1234 -> 45M
   | 1234 -> 45M                              | 2345 -> 15M
   | 2345 -> 15M                              | _ -> failwith "Unexpected"
   | productID -> failwith "Unexpected"     member __.Save(_,_) =
   )                                          failwith "Not implemented"
   .Create()                              }




F# Object Expressions
FOQ MOCKING
F# as a Testing Language
WTF
// Arrange
let xs =
   Mock<IList<char>>.With(fun xs ->
      <@ xs.Count --> 2
          xs.Item(0) --> '0'
          xs.Item(1) --> '1'
          xs.Contains(any()) --> true
          xs.RemoveAt(2) ==> System.ArgumentOutOfRangeException()
      @>
   )
// Assert
Assert.AreEqual(2, xs.Count)
Assert.AreEqual('0', xs.Item(0))
Assert.AreEqual('1', xs.Item(1))
Assert.IsTrue(xs.Contains('0'))
Assert.Throws<System.ArgumentOutOfRangeException>(fun () ->
   xs.RemoveAt(2)
)




Foq: IList<char>
var order =
   new Mock<IOrder>()
         .SetupProperties(new {
            Price = 99.99M,
            Quantity = 10,
            Side = Side.Bid,
            TimeInForce = TimeInForce.GoodTillCancel
         })
   .Create();
Assert.AreEqual(99.99M, order.Price);
Assert.AreEqual(10, order.Quantity);
Assert.AreEqual(Side.Bid, order.Side);
Assert.AreEqual(TimeInForce.GoodTillCancel,
order.TimeInForce);




Foq: Anonymous Type
let [<Test>] ``order sends mail if unfilled`` () =
    // setup data
    let order = Order("TALISKER", 51)
    let mailer = mock()
    order.SetMailer(mailer)
    // exercise
    order.Fill(mock())
    // verify
    verify <@ mailer.Send(any()) @> once




Foq: Type Inference
let [<Test>] ``verify sequence of calls`` () =
    // Arrange
    let xs = Mock.Of<IList<int>>()
    // Act
    xs.Clear()
    xs.Add(1)
    // Assert
    Mock.VerifySequence
        <@ xs.Clear()
           xs.Add(any()) @>




Foq Sequences
FOQ DEPLOYMENT
F# as a Testing language
Nuget Dowload   CodePlex Download




Deployment
FOQ API
F# as a testing language
Setup a mock method in C# with a lambda expression:

new Mock<IList<int>>()
 .Setup(x => x.Contains(It.IsAny<int>())).Returns(true)
 .Create();

Setup a mock method in F# with a Code Quotation:

Mock<System.Collections.IList>()
 .Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)
 .Create()


LINQ or
Quotations
Fluent Interface or
Functions
FOQ IMPLEMENTATION
F# as a testing language
Moq                 FakeItEasy
Total 16454         Total 11550
{ or } 2481         { or } 2948
Blank 1933          Blank 1522
Null checks 163     Null checks 92
Comments 7426       Comments 2566
Useful lines 4451   Useful lines 4422




LOC: Moq vs FakeItEasy
Fock v0.1      Fock v0.2
127 Lines      200 Lines
• Interfaces   • Interfaces
• Methods      • Abstract Classes
• Properties   • Methods
               • Properties
               • Raise Exceptions




Fock (aka Foq)
Foq.fs           Foq.fs + Foq.Linq.fs
Total 666        Total 933




LOC: Foq 0.8.1
QUESTIONS
F# as a Testing Language
What The Foq?

More Related Content

What's hot

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mqJeff Peck
 
Fondamentaux java
Fondamentaux javaFondamentaux java
Fondamentaux javaInes Ouaz
 
La programmation modulaire en Python
La programmation modulaire en PythonLa programmation modulaire en Python
La programmation modulaire en PythonABDESSELAM ARROU
 
POO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et PolymorphismePOO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et PolymorphismeMouna Torjmen
 
POO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationPOO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationMouna Torjmen
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring BatchAntoine Rey
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task QueueDuy Do
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Cohesion et couplage
Cohesion et couplage Cohesion et couplage
Cohesion et couplage Ahmed HARRAK
 

What's hot (20)

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mq
 
Fondamentaux java
Fondamentaux javaFondamentaux java
Fondamentaux java
 
Support de cours angular
Support de cours angularSupport de cours angular
Support de cours angular
 
Hibernate jpa
Hibernate jpaHibernate jpa
Hibernate jpa
 
La programmation modulaire en Python
La programmation modulaire en PythonLa programmation modulaire en Python
La programmation modulaire en Python
 
POO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et PolymorphismePOO Java Chapitre 4 Heritage et Polymorphisme
POO Java Chapitre 4 Heritage et Polymorphisme
 
POO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationPOO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 Encapsulation
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring Batch
 
Support POO Java première partie
Support POO Java première partieSupport POO Java première partie
Support POO Java première partie
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Support POO Java Deuxième Partie
Support POO Java Deuxième PartieSupport POO Java Deuxième Partie
Support POO Java Deuxième Partie
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Cohesion et couplage
Cohesion et couplage Cohesion et couplage
Cohesion et couplage
 

Similar to Unit Testing with Foq

Dublin ALT.NET session Thu Oct 24 2013
Dublin ALT.NET session Thu Oct 24 2013Dublin ALT.NET session Thu Oct 24 2013
Dublin ALT.NET session Thu Oct 24 2013Ruben Bartelink
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAnanth PackkilDurai
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Spocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderJAXLondon2014
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular TestingRussel Winder
 
Spocktacular testing
Spocktacular testingSpocktacular testing
Spocktacular testingRussel Winder
 

Similar to Unit Testing with Foq (20)

Dublin ALT.NET session Thu Oct 24 2013
Dublin ALT.NET session Thu Oct 24 2013Dublin ALT.NET session Thu Oct 24 2013
Dublin ALT.NET session Thu Oct 24 2013
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Python testing
Python  testingPython  testing
Python testing
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduce
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
Spocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel Winder
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular Testing
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Spocktacular testing
Spocktacular testingSpocktacular testing
Spocktacular testing
 

More from Phillip Trelford

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developerPhillip Trelford
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015Phillip Trelford
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Phillip Trelford
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015Phillip Trelford
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Phillip Trelford
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015Phillip Trelford
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Phillip Trelford
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Phillip Trelford
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015Phillip Trelford
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Phillip Trelford
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015Phillip Trelford
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015Phillip Trelford
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015Phillip Trelford
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015Phillip Trelford
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015Phillip Trelford
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014Phillip Trelford
 

More from Phillip Trelford (20)

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developer
 
Mobile F#un
Mobile F#unMobile F#un
Mobile F#un
 
F# eXchange Keynote 2016
F# eXchange Keynote 2016F# eXchange Keynote 2016
F# eXchange Keynote 2016
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015
 
Real World F# - SDD 2015
Real World F# -  SDD 2015Real World F# -  SDD 2015
Real World F# - SDD 2015
 
F# for C# devs - SDD 2015
F# for C# devs - SDD 2015F# for C# devs - SDD 2015
F# for C# devs - SDD 2015
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014
 

Recently uploaded

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 

Recently uploaded (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 

Unit Testing with Foq

  • 1. Unit Testing with Foq @ptrelford on @c4fsharp March 2013 Go download on Nuget or foq.codeplex.com
  • 3. what should a language for writing acceptance tests be? A Language for Testing
  • 4. Tests operate by example they describe specific scenarios and responses A Language for Testing
  • 5. I wonder if a different kind of programming language is required. - Martin Fowler 2003 A Language for Testing
  • 6. UNIT TESTING WITH F# F# as a Testing Language
  • 7. F# NUnit C# NUnit module MathTest = using NUnit.Framework; open NUnit.Framework [TestFixture] public class MathTest { let [<Test>] ``2 + 2 should equal 4``() = [Test] Assert.AreEqual(2 + 2, 4) public void TwoPlusTwoShouldEqualFour() { Assert.AreEqual(2 + 2, 4); } } NUnit
  • 8. let [<Test>] ``2 + 2 should equal 4``() = 2 + 2 |> should equal 4 FsUnit
  • 9. let [<Test>] ``2 + 2 should equal 4``() = test <@ 2 + 2 = 4 @> Unquote
  • 10. .NET MOCKING F# as a Testing Language
  • 13. var mock = new Mock<ILoveThisFramework>(); // WOW! No record/replay weirdness?! :) mock.Setup(framework => framework.DownloadExists("2.0.0.0")) .Returns(true) .AtMostOnce(); // Hand mock.Object as a collaborator and exercise it, // like calling methods on it... ILoveThisFramework lovable = mock.Object; bool download = lovable.DownloadExists("2.0.0.0"); // Verify that the given method was indeed called with the expected value mock.Verify(framework => framework.DownloadExists("2.0.0.0")); Moq
  • 14. // Creating a fake object is just dead easy! // No mocks, no stubs, everything's a fake! var lollipop = A.Fake<ICandy>(); var shop = A.Fake<ICandyShop>(); // To set up a call to return a value is also simple: A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop); // Use your fake as you would an actual instance of the faked type. var developer = new SweetTooth(); developer.BuyTastiestCandy(shop); // Asserting uses the exact same syntax as when configuring calls, // no need to teach yourself another syntax. A.CallTo(() => shop.BuyCandy(lollipop)).MustHaveHappened(); FakeItEasy
  • 15. Mock object Object Expression Mock<IShopDataAccess>() { new IShopDataAccess with .Setup(fun data -> member __.GetProductPrice(productId) = <@ data.GetProductPrice(any()) @>) match productId with .Calls<int>(function | 1234 -> 45M | 1234 -> 45M | 2345 -> 15M | 2345 -> 15M | _ -> failwith "Unexpected" | productID -> failwith "Unexpected" member __.Save(_,_) = ) failwith "Not implemented" .Create() } F# Object Expressions
  • 16. FOQ MOCKING F# as a Testing Language
  • 17. WTF
  • 18. // Arrange let xs = Mock<IList<char>>.With(fun xs -> <@ xs.Count --> 2 xs.Item(0) --> '0' xs.Item(1) --> '1' xs.Contains(any()) --> true xs.RemoveAt(2) ==> System.ArgumentOutOfRangeException() @> ) // Assert Assert.AreEqual(2, xs.Count) Assert.AreEqual('0', xs.Item(0)) Assert.AreEqual('1', xs.Item(1)) Assert.IsTrue(xs.Contains('0')) Assert.Throws<System.ArgumentOutOfRangeException>(fun () -> xs.RemoveAt(2) ) Foq: IList<char>
  • 19. var order = new Mock<IOrder>() .SetupProperties(new { Price = 99.99M, Quantity = 10, Side = Side.Bid, TimeInForce = TimeInForce.GoodTillCancel }) .Create(); Assert.AreEqual(99.99M, order.Price); Assert.AreEqual(10, order.Quantity); Assert.AreEqual(Side.Bid, order.Side); Assert.AreEqual(TimeInForce.GoodTillCancel, order.TimeInForce); Foq: Anonymous Type
  • 20. let [<Test>] ``order sends mail if unfilled`` () = // setup data let order = Order("TALISKER", 51) let mailer = mock() order.SetMailer(mailer) // exercise order.Fill(mock()) // verify verify <@ mailer.Send(any()) @> once Foq: Type Inference
  • 21. let [<Test>] ``verify sequence of calls`` () = // Arrange let xs = Mock.Of<IList<int>>() // Act xs.Clear() xs.Add(1) // Assert Mock.VerifySequence <@ xs.Clear() xs.Add(any()) @> Foq Sequences
  • 22. FOQ DEPLOYMENT F# as a Testing language
  • 23. Nuget Dowload CodePlex Download Deployment
  • 24. FOQ API F# as a testing language
  • 25. Setup a mock method in C# with a lambda expression: new Mock<IList<int>>() .Setup(x => x.Contains(It.IsAny<int>())).Returns(true) .Create(); Setup a mock method in F# with a Code Quotation: Mock<System.Collections.IList>() .Setup(fun x -> <@ x.Contains(any()) @>).Returns(true) .Create() LINQ or Quotations
  • 27. FOQ IMPLEMENTATION F# as a testing language
  • 28. Moq FakeItEasy Total 16454 Total 11550 { or } 2481 { or } 2948 Blank 1933 Blank 1522 Null checks 163 Null checks 92 Comments 7426 Comments 2566 Useful lines 4451 Useful lines 4422 LOC: Moq vs FakeItEasy
  • 29. Fock v0.1 Fock v0.2 127 Lines 200 Lines • Interfaces • Interfaces • Methods • Abstract Classes • Properties • Methods • Properties • Raise Exceptions Fock (aka Foq)
  • 30. Foq.fs Foq.fs + Foq.Linq.fs Total 666 Total 933 LOC: Foq 0.8.1
  • 31. QUESTIONS F# as a Testing Language

Editor's Notes

  1. http://martinfowler.com/bliki/TestingLanguage.html
  2. http://nugetmusthaves.com/Tag/mocking