SlideShare a Scribd company logo
AMIR BARYLKO
                          TDD PATTERNS
                       FOR .NET DEVELOPERS
                                       SDEC 2010
                              DEVELOPER FOUNDATION TRACK




Amir Barylko - TDD Patterns                            MavenThought Inc.
Wednesday, October 13, 2010
WHO AM I?

    • Architect

    • Developer

    • Mentor

    • Great            cook

    • The          one who’s entertaining you for the next hour!


Amir Barylko - TDD Patterns                                        MavenThought Inc.
Wednesday, October 13, 2010
WHY TDD?

    • Test         first approach

    • Quality                 driven

    • Easy          to refactor

    • Regression                 tests as byproduct

    • Increase                developer’s confidence


Amir Barylko - TDD Patterns                           MavenThought Inc.
Wednesday, October 13, 2010
SETUP
                                 Tools
                              AutoMocking
                              Movie Library




Amir Barylko - TDD Patterns                   MavenThought Inc.
Wednesday, October 13, 2010
TOOLS

    •   Testing framework: NUnit, MbUnit, MSpec, rSpec

    •   Mocking framework: Rhino Mocks, Moq, TypeMock, nSubstitute

    •   Test Automation: Scripts that can run the test from the developer
        computer.

    •   CI server: Unit test should be run after each commit, integration
        tests, schedule tests.

    •   Reports and Notifications: The team should realize right away that
        the tests are broken (broke the build jar).
Amir Barylko - TDD Patterns                                      MavenThought Inc.
Wednesday, October 13, 2010
MOVIE LIBRARY




Amir Barylko - TDD Patterns                   MavenThought Inc.
Wednesday, October 13, 2010
AUTO MOCKING

    • Automatic               dependency creation for System Under Test

    • Dictionary              of dependencies to reuse by type

    • Faster            setup of tests without specifying creation

    • Build          your own: StructureMap

    • Or        use MavenThought Testing

    • What             about too many dependencies?
Amir Barylko - TDD Patterns                                          MavenThought Inc.
Wednesday, October 13, 2010
BEFORE AUTOMOCKING
    protected IStorage Storage { get; set; }              Define SUT
    protected ICritic Critic { get; set }               & Dependencies
    protected MovieLibrary Sut { get; set; }

    public void Setup()
    {                                                 Initialize each
        this.Storage = Mock<IStorage>();

             this.Critic = Mock<ICritic>();

             this.Sut = new MovieLibrary(this.Storage, this.Critic)
    }




Amir Barylko - TDD Patterns                                       MavenThought Inc.
Wednesday, October 13, 2010
AFTER AUTOMOCKING
                                                          SUT
    public abstract class Specification
        : AutoMockSpecificationWithNoContract<MovieLibrary>
    {
    }

    public class When_movie_library_is_created : Specification
    {
        [It]
        public void Should_do_something_with_critic()
        {
             Dep<IMovieCritic>().AssertWasCalled(...);
        }
    }
                              Dependency


Amir Barylko - TDD Patterns                                   MavenThought Inc.
Wednesday, October 13, 2010
PATTERNS
              One feature at a time   Dependency Injection
                 State Check          Dependency Lookup
                   Behaviour               Database
                  Parameters              Smelly Test



Amir Barylko - TDD Patterns                         MavenThought Inc.
Wednesday, October 13, 2010
ONE FEATURE PER TEST

    • Easy          to approach                      Given That
                                                     (arrange)
    • Easy          to understand
                                                      When I Run
    • Easy          to maintain
                                                        (act)
    • Enforce                 Given, When, Then
                                                  Then it should ...
                                                       (assert)


Amir Barylko - TDD Patterns                                  MavenThought Inc.
Wednesday, October 13, 2010
XUNIT UNIT TESTING
    [TestFixture]
    public class MovieLibraryTest
    {
        private MockRepository _mockery;
        private Library _library;
        private IMovieCritic _critic;
                                                    [Test]
           [SetUp]
                                                    public void WhenXXXX()
           public void BeforeEachTest()
                                                    {
           {
                                                        Assert.IsEmpty(_library.Contents);
               this._mockery = new Mockery();
                                                    }
               this._critic = _mockery.Create...;
               this._library = new Library...
                                                    [Test]
           }
                                                    public void WhenYYYYAndZZZAndWWWW()
                                                    {
           [TearDown]
                                                        // record, playback, assert
           public void AfterEachTest()
                                                    }
           {
               this._library.Clear();
           }




Amir Barylko - TDD Patterns                                                 MavenThought Inc.
Wednesday, October 13, 2010
ARRANGE ACT ASSERT
             [Test]
             public void When_Adding_Should_Appear_In_The_Contents()
             {
                 // Arrange
                 var before = _sut.Contents.Count();

                      // Act
                      _sut.Add(_movie1);

                      // Assert
                      Assert.Contains(_sut.Contents, _movie1);
                      Assert.AreEqual(before + 1, _sut.Contents.Count());
             }



Amir Barylko - TDD Patterns                                           MavenThought Inc.
Wednesday, October 13, 2010
ONE FEATURE
                              MANY SCENARIOS
        Feature Specification

                  When_xxxx.cs

                   When_yyyy.cs

                   When_zzzz.cs




Amir Barylko - TDD Patterns                    MavenThought Inc.
Wednesday, October 13, 2010
FOCUS
    [Specification]
    public class When_movie_library_is_cleared : MovieLibrarySpecification
    {
        protected override void WhenIRun()
        {
            AddLotsOfMovies();

                     this.Sut.Clear();
            }

            [It]
            public void Should_have_no_movies_in_the_library()
            {
                 this.Sut.Contents.Should().Be.Empty();
            }
    }


Amir Barylko - TDD Patterns                                      MavenThought Inc.
Wednesday, October 13, 2010
CHECK THAT STATE!

    • Care           about the end state   var m = new Library...

    • Does     not validate SUT
        transitions                              Run Test

    • Verify the state agains the
                                            m.Count.Should(...)
        expected value




Amir Barylko - TDD Patterns                             MavenThought Inc.
Wednesday, October 13, 2010
WHY CHECK
                              IMPLEMENTATION?
    [Specification]
    public class When_movie_library_lists_non_violent_movies
             : MovieLibrarySpecification
    {
             [It]
             public void Should_call_the_critic()
             {
                    Dep<IMovieCritic>().AssertWasCalled(c => c.IsViolent(...));
             }
    }



Amir Barylko - TDD Patterns                                          MavenThought Inc.
Wednesday, October 13, 2010
EXPECTED STATE
    [Specification]
    public class When_movie_library_lists_non_violent_movies
             : MovieLibrarySpecification
    {
             [It]
             public void Should_return_all_the_non_violent_movies()
             {
                      this._actual.Should().Have.SameSequenceAs(this._expected);
             }
    }


Amir Barylko - TDD Patterns                                           MavenThought Inc.
Wednesday, October 13, 2010
BEHAVIOUR IS EVERYTHING

    • Checking   the expected          var m = Mock<...>
        behaviour happened

    • Uses           mock objects         m.Stub(...)

    • The    behaviour is specified
        for each mock object               Run Test


    • The   expected methods
                                     m.AssertWasCalled(...)
        should be called

Amir Barylko - TDD Patterns                       MavenThought Inc.
Wednesday, October 13, 2010
HOW ABOUT EVENTS?

    • Where                   is the state?

    • Should              I create a concrete class?
         [It]

         public void Should_notify_an_element_was_added()
         {
                  .......????
         }




Amir Barylko - TDD Patterns                                 MavenThought Inc.
Wednesday, October 13, 2010
ASSERT BEHAVIOR
    protected override void GivenThat()
    {
        base.GivenThat();

           this._handler = MockIt(this._handler);

           this.Sut.Added += this._handler;
    }

    [It]
    public void Should_notify_an_element_was_added()
    {
           var matching = ...;
           this._handler.AssertWasCalled(h => h(Arg.Is(this.Sut), matching));
    }



Amir Barylko - TDD Patterns                                               MavenThought Inc.
Wednesday, October 13, 2010
PARAMETERS & FACTORIES
                                             [Row(1)]
    • Avoid    duplication and               [Row(2)]
        repetition                           void Method(int arg)
                                             [Row(typeof(...))]
    • Generic                 Parameters     void Method<T>(...)

    • Parameters                 Factories   [Factory(...)]
                                             void Method(string arg)
    • Random                  strings        void Method([Random]...)

    • Random                  numbers        void Method([Random]...,
                                                         [Factory]...)

Amir Barylko - TDD Patterns                                  MavenThought Inc.
Wednesday, October 13, 2010
COMBINE
    public When_movie_is_created(
         [RandomStrings(Count=5, Pattern="The great [A-Za-z]{8}")] string title,
         [Factory("RandomDates")] DateTime releaseDate)
    {
           this._title = title;
           this._releaseDate = releaseDate;
    }




Amir Barylko - TDD Patterns                                              MavenThought Inc.
Wednesday, October 13, 2010
DEPENDENCY INJECTION

    • Remove   hardcoded                   Initialize dependency
        dependencies

    • Introduces   dependency in           Stub dependency with
        the constructor / setter                   mock

    • Easy          to test and maintain
                                           Assert the mock is
                                                returned
    •S       OLID


Amir Barylko - TDD Patterns                             MavenThought Inc.
Wednesday, October 13, 2010
HARDCODED
                              DEPENDENCIES
    public MovieLibrary()
    {
             this.Critic = new MovieCritic();
             this._posterService = new SimplePosterService();
    }


                                                How are we going
                                                   to test it?




Amir Barylko - TDD Patterns                                     MavenThought Inc.
Wednesday, October 13, 2010
INJECT DEPENDENCIES
    public MovieLibrary(IMovieCritic critic,

             IPosterService posterService,

             IMovieFactory factory)

             : this(critic)

    {

             this._posterService = posterService;

             this._factory = factory;

    }




Amir Barylko - TDD Patterns                         MavenThought Inc.
Wednesday, October 13, 2010
DEPENDENCY LOOKUP

    • Remove   hardcoded                    Initialize service
        dependencies                             locator

    • Introduces    a factory or           Stub to return a mock
        service locator

    • Easy          to test and maintain    Assert the mock is
                                                 returned
    •S       OLID


Amir Barylko - TDD Patterns                             MavenThought Inc.
Wednesday, October 13, 2010
HARDCODED SERVICE
    public void Import(IDictionary<string, DateTime> movies)

    {

             movies.ForEach(pair => this.Add(new Movie(...)));

    }

                                                      Hardcoded!!!




Amir Barylko - TDD Patterns                                      MavenThought Inc.
Wednesday, October 13, 2010
FACTORY
    public void Import(IDictionary<string, DateTime> movies)
    {
             movies.ForEach(pair => this.Add(this._factory.Create(...)));
    }


                                                     COULD BE A
                                                  SERVICE LOCATOR....




Amir Barylko - TDD Patterns                                      MavenThought Inc.
Wednesday, October 13, 2010
DATABASE TESTING

    • Base   class to setup the           Create Database
        database

    • The    test always works with a         Populate
        clean database

    • Can   be configured to                    Store
        populate data if needed

    • To                                 Retrieve and Assert
               test only DB operations

Amir Barylko - TDD Patterns                            MavenThought Inc.
Wednesday, October 13, 2010
USE TEMPORARY FILES
    protected BaseStorageSpecification()
    {
           DbFile = Path.GetTempFileName();
    }


    protected override ISessionFactory CreateSut()
    {
           var factory = SessionFactoryGateway.CreateSessionFactory(SQLiteConfiguration
                                                                        .Standard
                                                                        .UsingFile(DbFile)
                                                                        .ShowSql(), BuildSchema);


           return factory;
    }




Amir Barylko - TDD Patterns                                                         MavenThought Inc.
Wednesday, October 13, 2010
CREATE & POPULATE
    private void BuildSchema(Configuration config)
    {
            // delete the existing db on each run
            if (File.Exists(DbFile))
            {
                     File.Delete(DbFile);
            }


            // export schema
            new SchemaExport(config).Create(true, true);
    }



Amir Barylko - TDD Patterns                                MavenThought Inc.
Wednesday, October 13, 2010
TEST DB OPERATIONS
    [ConstructorSpecification]
    public class When_movie_is_created : PersistentMovieSpecification
    {
          /// <summary>
          /// Validates the mapping
          /// </summary>
          [It]
          public void Should_have_the_right_mappings()
          {
                 this.Sut.AutoSession(s =>
                                             new PersistenceSpecification<Movie>(s)
                                                 .CheckProperty(p => p.Title, "Space Balls")
                                                 .VerifyTheMappings());
          }
    }




Amir Barylko - TDD Patterns                                                                    MavenThought Inc.
Wednesday, October 13, 2010
OMG: WHAT’S THAT SMELL?

    • Setup            is too big        • Write   only tests

    • Hard   to understand               • Tests   List<T>
        dependencies
                                         • Checking    state between calls
    • Needs   SQL server running
        with MsQueue and Biztalk         • Inspect   internals of the class

    • Code             coverage rules!   • Can’t   write a test for that

                                         • No   automation is possible
Amir Barylko - TDD Patterns                                      MavenThought Inc.
Wednesday, October 13, 2010
QUESTIONS?




Amir Barylko - TDD Patterns                MavenThought Inc.
Wednesday, October 13, 2010
THANK YOU!

    • Contact                 me: amir@barylko.com, @abarylko

    • Download: http://www.orhtocoders.com/presentations

    • Books: The                rSpec book, xUnit Patterns.




Amir Barylko - TDD Patterns                                     MavenThought Inc.
Wednesday, October 13, 2010
RESOURCES

    • NUnit: http://www.nunit.org

    • Gallio           & MbUnit: http://www.gallio.org

    • MavenThought Testing: http://maventcommons.codeplex.com

    • Rhino            Mocks: http://www.ayende.com

    • StructureMap: http://structuremap.sourcefore.com

    • TeamCity: http://www.jetbrains.com

Amir Barylko - TDD Patterns                              MavenThought Inc.
Wednesday, October 13, 2010

More Related Content

PDF
dojo is bizarro jQuery
PDF
iPhone Memory Management
PDF
Invokedynamic: Tales from the Trenches
PDF
Invokedynamic in 45 Minutes
PDF
JavaScript with YUI
PDF
Lecture 03
PDF
Collections
PDF
CPL12-Agile-planning
dojo is bizarro jQuery
iPhone Memory Management
Invokedynamic: Tales from the Trenches
Invokedynamic in 45 Minutes
JavaScript with YUI
Lecture 03
Collections
CPL12-Agile-planning

Similar to Tdd patterns1 (20)

PDF
prdc10-tdd-patterns
PDF
Need(le) for Speed - Effective Unit Testing for Java EE
PDF
Robotium Tutorial
PDF
Codemash-advanced-ioc-castle-windsor
PPTX
Mini training - Moving to xUnit.net
PDF
ioc-castle-windsor
PDF
PRDC11-tdd-common-mistakes
PDF
Learn How to Unit Test Your Android Application (with Robolectric)
PDF
Escaping Automated Test Hell - One Year Later
PDF
An Introduction To Unit Testing and TDD
PDF
1_mockito
ODP
Using Mockito
PDF
Akka scalaliftoff london_2010
PDF
XQuery Design Patterns
PDF
How and what to unit test
PDF
Level Up Your Integration Testing With Testcontainers
PDF
Implementing Quality on Java projects
PDF
Reef - ESUG 2010
PDF
Abstracting databases access in Titanium Mobile
PDF
2011 codestrong-abstracting-databases-access-in-titanium-mobile
prdc10-tdd-patterns
Need(le) for Speed - Effective Unit Testing for Java EE
Robotium Tutorial
Codemash-advanced-ioc-castle-windsor
Mini training - Moving to xUnit.net
ioc-castle-windsor
PRDC11-tdd-common-mistakes
Learn How to Unit Test Your Android Application (with Robolectric)
Escaping Automated Test Hell - One Year Later
An Introduction To Unit Testing and TDD
1_mockito
Using Mockito
Akka scalaliftoff london_2010
XQuery Design Patterns
How and what to unit test
Level Up Your Integration Testing With Testcontainers
Implementing Quality on Java projects
Reef - ESUG 2010
Abstracting databases access in Titanium Mobile
2011 codestrong-abstracting-databases-access-in-titanium-mobile
Ad

More from Amir Barylko (20)

PDF
Functional converter project
PDF
Elm: delightful web development
PDF
Dot Net Core
PDF
No estimates
PDF
User stories deep dive
PDF
Coderetreat hosting training
PDF
There's no charge for (functional) awesomeness
PDF
What's new in c# 6
PDF
Productive teams
PDF
Who killed object oriented design?
PDF
From coach to owner - What I learned from the other side
PDF
Communication is the Key to Teamwork and productivity
PDF
Acceptance Test Driven Development
PDF
Refactoring
PDF
Agile requirements
PDF
Agile teams and responsibilities
PDF
Refactoring
PDF
Beutiful javascript with coffeescript
PDF
Sass & bootstrap
PDF
Rich UI with Knockout.js &amp; Coffeescript
Functional converter project
Elm: delightful web development
Dot Net Core
No estimates
User stories deep dive
Coderetreat hosting training
There's no charge for (functional) awesomeness
What's new in c# 6
Productive teams
Who killed object oriented design?
From coach to owner - What I learned from the other side
Communication is the Key to Teamwork and productivity
Acceptance Test Driven Development
Refactoring
Agile requirements
Agile teams and responsibilities
Refactoring
Beutiful javascript with coffeescript
Sass & bootstrap
Rich UI with Knockout.js &amp; Coffeescript
Ad

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Chapter 3 Spatial Domain Image Processing.pdf
Spectral efficient network and resource selection model in 5G networks
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
MIND Revenue Release Quarter 2 2025 Press Release
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
Unlocking AI with Model Context Protocol (MCP)
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Tdd patterns1

  • 1. AMIR BARYLKO TDD PATTERNS FOR .NET DEVELOPERS SDEC 2010 DEVELOPER FOUNDATION TRACK Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 2. WHO AM I? • Architect • Developer • Mentor • Great cook • The one who’s entertaining you for the next hour! Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 3. WHY TDD? • Test first approach • Quality driven • Easy to refactor • Regression tests as byproduct • Increase developer’s confidence Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 4. SETUP Tools AutoMocking Movie Library Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 5. TOOLS • Testing framework: NUnit, MbUnit, MSpec, rSpec • Mocking framework: Rhino Mocks, Moq, TypeMock, nSubstitute • Test Automation: Scripts that can run the test from the developer computer. • CI server: Unit test should be run after each commit, integration tests, schedule tests. • Reports and Notifications: The team should realize right away that the tests are broken (broke the build jar). Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 6. MOVIE LIBRARY Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 7. AUTO MOCKING • Automatic dependency creation for System Under Test • Dictionary of dependencies to reuse by type • Faster setup of tests without specifying creation • Build your own: StructureMap • Or use MavenThought Testing • What about too many dependencies? Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 8. BEFORE AUTOMOCKING protected IStorage Storage { get; set; } Define SUT protected ICritic Critic { get; set } & Dependencies protected MovieLibrary Sut { get; set; } public void Setup() { Initialize each this.Storage = Mock<IStorage>(); this.Critic = Mock<ICritic>(); this.Sut = new MovieLibrary(this.Storage, this.Critic) } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 9. AFTER AUTOMOCKING SUT public abstract class Specification : AutoMockSpecificationWithNoContract<MovieLibrary> { } public class When_movie_library_is_created : Specification { [It] public void Should_do_something_with_critic() { Dep<IMovieCritic>().AssertWasCalled(...); } } Dependency Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 10. PATTERNS One feature at a time Dependency Injection State Check Dependency Lookup Behaviour Database Parameters Smelly Test Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 11. ONE FEATURE PER TEST • Easy to approach Given That (arrange) • Easy to understand When I Run • Easy to maintain (act) • Enforce Given, When, Then Then it should ... (assert) Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 12. XUNIT UNIT TESTING [TestFixture] public class MovieLibraryTest { private MockRepository _mockery; private Library _library; private IMovieCritic _critic; [Test] [SetUp] public void WhenXXXX() public void BeforeEachTest() { { Assert.IsEmpty(_library.Contents); this._mockery = new Mockery(); } this._critic = _mockery.Create...; this._library = new Library... [Test] } public void WhenYYYYAndZZZAndWWWW() { [TearDown] // record, playback, assert public void AfterEachTest() } { this._library.Clear(); } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 13. ARRANGE ACT ASSERT [Test] public void When_Adding_Should_Appear_In_The_Contents() { // Arrange var before = _sut.Contents.Count(); // Act _sut.Add(_movie1); // Assert Assert.Contains(_sut.Contents, _movie1); Assert.AreEqual(before + 1, _sut.Contents.Count()); } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 14. ONE FEATURE MANY SCENARIOS Feature Specification When_xxxx.cs When_yyyy.cs When_zzzz.cs Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 15. FOCUS [Specification] public class When_movie_library_is_cleared : MovieLibrarySpecification { protected override void WhenIRun() { AddLotsOfMovies(); this.Sut.Clear(); } [It] public void Should_have_no_movies_in_the_library() { this.Sut.Contents.Should().Be.Empty(); } } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 16. CHECK THAT STATE! • Care about the end state var m = new Library... • Does not validate SUT transitions Run Test • Verify the state agains the m.Count.Should(...) expected value Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 17. WHY CHECK IMPLEMENTATION? [Specification] public class When_movie_library_lists_non_violent_movies : MovieLibrarySpecification { [It] public void Should_call_the_critic() { Dep<IMovieCritic>().AssertWasCalled(c => c.IsViolent(...)); } } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 18. EXPECTED STATE [Specification] public class When_movie_library_lists_non_violent_movies : MovieLibrarySpecification { [It] public void Should_return_all_the_non_violent_movies() { this._actual.Should().Have.SameSequenceAs(this._expected); } } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 19. BEHAVIOUR IS EVERYTHING • Checking the expected var m = Mock<...> behaviour happened • Uses mock objects m.Stub(...) • The behaviour is specified for each mock object Run Test • The expected methods m.AssertWasCalled(...) should be called Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 20. HOW ABOUT EVENTS? • Where is the state? • Should I create a concrete class? [It] public void Should_notify_an_element_was_added() { .......???? } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 21. ASSERT BEHAVIOR protected override void GivenThat() { base.GivenThat(); this._handler = MockIt(this._handler); this.Sut.Added += this._handler; } [It] public void Should_notify_an_element_was_added() { var matching = ...; this._handler.AssertWasCalled(h => h(Arg.Is(this.Sut), matching)); } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 22. PARAMETERS & FACTORIES [Row(1)] • Avoid duplication and [Row(2)] repetition void Method(int arg) [Row(typeof(...))] • Generic Parameters void Method<T>(...) • Parameters Factories [Factory(...)] void Method(string arg) • Random strings void Method([Random]...) • Random numbers void Method([Random]..., [Factory]...) Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 23. COMBINE public When_movie_is_created( [RandomStrings(Count=5, Pattern="The great [A-Za-z]{8}")] string title, [Factory("RandomDates")] DateTime releaseDate) { this._title = title; this._releaseDate = releaseDate; } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 24. DEPENDENCY INJECTION • Remove hardcoded Initialize dependency dependencies • Introduces dependency in Stub dependency with the constructor / setter mock • Easy to test and maintain Assert the mock is returned •S OLID Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 25. HARDCODED DEPENDENCIES public MovieLibrary() { this.Critic = new MovieCritic(); this._posterService = new SimplePosterService(); } How are we going to test it? Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 26. INJECT DEPENDENCIES public MovieLibrary(IMovieCritic critic, IPosterService posterService, IMovieFactory factory) : this(critic) { this._posterService = posterService; this._factory = factory; } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 27. DEPENDENCY LOOKUP • Remove hardcoded Initialize service dependencies locator • Introduces a factory or Stub to return a mock service locator • Easy to test and maintain Assert the mock is returned •S OLID Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 28. HARDCODED SERVICE public void Import(IDictionary<string, DateTime> movies) { movies.ForEach(pair => this.Add(new Movie(...))); } Hardcoded!!! Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 29. FACTORY public void Import(IDictionary<string, DateTime> movies) { movies.ForEach(pair => this.Add(this._factory.Create(...))); } COULD BE A SERVICE LOCATOR.... Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 30. DATABASE TESTING • Base class to setup the Create Database database • The test always works with a Populate clean database • Can be configured to Store populate data if needed • To Retrieve and Assert test only DB operations Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 31. USE TEMPORARY FILES protected BaseStorageSpecification() { DbFile = Path.GetTempFileName(); } protected override ISessionFactory CreateSut() { var factory = SessionFactoryGateway.CreateSessionFactory(SQLiteConfiguration .Standard .UsingFile(DbFile) .ShowSql(), BuildSchema); return factory; } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 32. CREATE & POPULATE private void BuildSchema(Configuration config) { // delete the existing db on each run if (File.Exists(DbFile)) { File.Delete(DbFile); } // export schema new SchemaExport(config).Create(true, true); } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 33. TEST DB OPERATIONS [ConstructorSpecification] public class When_movie_is_created : PersistentMovieSpecification { /// <summary> /// Validates the mapping /// </summary> [It] public void Should_have_the_right_mappings() { this.Sut.AutoSession(s => new PersistenceSpecification<Movie>(s) .CheckProperty(p => p.Title, "Space Balls") .VerifyTheMappings()); } } Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 34. OMG: WHAT’S THAT SMELL? • Setup is too big • Write only tests • Hard to understand • Tests List<T> dependencies • Checking state between calls • Needs SQL server running with MsQueue and Biztalk • Inspect internals of the class • Code coverage rules! • Can’t write a test for that • No automation is possible Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 35. QUESTIONS? Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 36. THANK YOU! • Contact me: amir@barylko.com, @abarylko • Download: http://www.orhtocoders.com/presentations • Books: The rSpec book, xUnit Patterns. Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010
  • 37. RESOURCES • NUnit: http://www.nunit.org • Gallio & MbUnit: http://www.gallio.org • MavenThought Testing: http://maventcommons.codeplex.com • Rhino Mocks: http://www.ayende.com • StructureMap: http://structuremap.sourcefore.com • TeamCity: http://www.jetbrains.com Amir Barylko - TDD Patterns MavenThought Inc. Wednesday, October 13, 2010