SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
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

Mais conteúdo relacionado

Semelhante a Tdd patterns1

prdc10-tdd-patterns
prdc10-tdd-patternsprdc10-tdd-patterns
prdc10-tdd-patternsAmir Barylko
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EEhwilming
 
Codemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsorCodemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsorAmir Barylko
 
ioc-castle-windsor
ioc-castle-windsorioc-castle-windsor
ioc-castle-windsorAmir Barylko
 
PRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesPRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesAmir Barylko
 
Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Marakana Inc.
 
Escaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year LaterEscaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year LaterWojciech Seliga
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Skills Matter
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersVMware Tanzu
 
Implementing Quality on Java projects
Implementing Quality on Java projectsImplementing Quality on Java projects
Implementing Quality on Java projectsVincent Massol
 
2011 codestrong-abstracting-databases-access-in-titanium-mobile
2011 codestrong-abstracting-databases-access-in-titanium-mobile2011 codestrong-abstracting-databases-access-in-titanium-mobile
2011 codestrong-abstracting-databases-access-in-titanium-mobileAxway Appcelerator
 
Abstracting databases access in Titanium Mobile
Abstracting databases access in Titanium MobileAbstracting databases access in Titanium Mobile
Abstracting databases access in Titanium MobileXavier Lacot
 

Semelhante a Tdd patterns1 (20)

prdc10-tdd-patterns
prdc10-tdd-patternsprdc10-tdd-patterns
prdc10-tdd-patterns
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EE
 
Robotium Tutorial
Robotium TutorialRobotium Tutorial
Robotium Tutorial
 
Codemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsorCodemash-advanced-ioc-castle-windsor
Codemash-advanced-ioc-castle-windsor
 
Mini training - Moving to xUnit.net
Mini training - Moving to xUnit.netMini training - Moving to xUnit.net
Mini training - Moving to xUnit.net
 
ioc-castle-windsor
ioc-castle-windsorioc-castle-windsor
ioc-castle-windsor
 
PRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakesPRDC11-tdd-common-mistakes
PRDC11-tdd-common-mistakes
 
Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)
 
Escaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year LaterEscaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year Later
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
1_mockito
1_mockito1_mockito
1_mockito
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Akka scalaliftoff london_2010
Akka scalaliftoff london_2010
 
XQuery Design Patterns
XQuery Design PatternsXQuery Design Patterns
XQuery Design Patterns
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Level Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With TestcontainersLevel Up Your Integration Testing With Testcontainers
Level Up Your Integration Testing With Testcontainers
 
Implementing Quality on Java projects
Implementing Quality on Java projectsImplementing Quality on Java projects
Implementing Quality on Java projects
 
Reef - ESUG 2010
Reef - ESUG 2010Reef - ESUG 2010
Reef - ESUG 2010
 
2011 codestrong-abstracting-databases-access-in-titanium-mobile
2011 codestrong-abstracting-databases-access-in-titanium-mobile2011 codestrong-abstracting-databases-access-in-titanium-mobile
2011 codestrong-abstracting-databases-access-in-titanium-mobile
 
Abstracting databases access in Titanium Mobile
Abstracting databases access in Titanium MobileAbstracting databases access in Titanium Mobile
Abstracting databases access in Titanium Mobile
 

Mais de Amir Barylko

Functional converter project
Functional converter projectFunctional converter project
Functional converter projectAmir Barylko
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web developmentAmir Barylko
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep diveAmir Barylko
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting trainingAmir Barylko
 
There's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessThere's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessAmir Barylko
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6Amir Barylko
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
From coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideFrom coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideAmir Barylko
 
Communication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityCommunication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityAmir Barylko
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven DevelopmentAmir Barylko
 
Agile requirements
Agile requirementsAgile requirements
Agile requirementsAmir Barylko
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilitiesAmir Barylko
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescriptAmir Barylko
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptAmir Barylko
 

Mais de Amir Barylko (20)

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

Último

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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 DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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...Enterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
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.pdfsudhanshuwaghmare1
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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 Takeoffsammart93
 
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 educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
[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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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.pdfUK Journal
 
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 MenDelhi Call girls
 

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
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
 

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