SlideShare ist ein Scribd-Unternehmen logo
1 von 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?

Weitere Àhnliche Inhalte

Was ist angesagt?

Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Sara Torkey
 

Was ist angesagt? (20)

Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Junit
JunitJunit
Junit
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
Open source APM Scouter로 ëȘšë‹ˆí„°ë§ 잘 하Ʞ
Open source APM Scouter로 ëȘšë‹ˆí„°ë§ 잘 하ꞰOpen source APM Scouter로 ëȘšë‹ˆí„°ë§ 잘 하Ʞ
Open source APM Scouter로 ëȘšë‹ˆí„°ë§ 잘 하Ʞ
 
SWTBot Tutorial
SWTBot TutorialSWTBot Tutorial
SWTBot Tutorial
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
react-js-notes-for-professionals-book.pdf
react-js-notes-for-professionals-book.pdfreact-js-notes-for-professionals-book.pdf
react-js-notes-for-professionals-book.pdf
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Kotlin - scope functions and collections
Kotlin - scope functions and collectionsKotlin - scope functions and collections
Kotlin - scope functions and collections
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Clean Code
Clean CodeClean Code
Clean Code
 
SwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made EasySwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made Easy
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Integration Testing with a Citrus twist
Integration Testing with a Citrus twistIntegration Testing with a Citrus twist
Integration Testing with a Citrus twist
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 

Ähnlich wie 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
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

KĂŒrzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

KĂŒrzlich hochgeladen (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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 Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.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

Hinweis der Redaktion

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