SlideShare una empresa de Scribd logo
1 de 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?

Más contenido relacionado

La actualidad más candente

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 

La actualidad más candente (20)

Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHP
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Core java
Core javaCore java
Core java
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Clean code
Clean codeClean code
Clean code
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Protocol Buffers
Protocol BuffersProtocol Buffers
Protocol Buffers
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 

Similar a Unit Testing with Foq

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
 
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
Robot Media
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
julien.ponge
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
elliando 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 MapReduce
Ananth PackkilDurai
 

Similar a 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
 

Más de Phillip 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 2015
Phillip 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 2015
Phillip Trelford
 

Más de 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
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

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

Notas del editor

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