SlideShare a Scribd company logo
Test Driven DevelopmentArrange, Act, Assert… AwesomeJason OffuttSoftware EngineerCentral Christian ChurchEmail: jason.offutt@cccev.comTwitter: @JasonOffutt #RefreshCache
What is TDD?It’s a development methodologyWrite automated test cases to define what your code should be doing
Write/Refactor code to satisfy test requirementsHow does it work?Write test case firstRun test (should fail)Write/Refactor code to satisfy test expectationsRun test again (should pass)???Profit
How does it work?To run these automated tests, we need a test framework.MS TestMicrosoft’s testing frameworkAble to run tests from within Visual Studio’s GUIComes out of the box with Visual Studio (Professional or higher)NUnitSimpler/Cleaner syntax than MS TestComes with it’s own client to run tests, just point it at an assemblyFree to download and use3rd party tools like ReSharper allow NUnit tests to be executed directly in Visual Studio
Test FirstThe goal is to write test cases to define expectations on how our code should behave.The result is that you end up with code that behaves in a predictable manner.In the end, you’ll have an entire suite of tests to prove your code works “correctly”.The first time we run a test, it should fail. We haven’t written any implementation to satisfy the test’s requirements yet.
What does a test look like?[Test]public voidIsValid_Should_Return_True_When_Foo_Has_Name(){// Arrangevar foo = new Foo();foo.Name = "Charlie";// Actvar result = foo.IsValid;// AssertAssert.IsTrue(result);}
What does a test look like?[Test]public voidIsValid_Should_Return_True_When_Foo_Has_Name(){// Arrangevar foo = new Foo();foo.Name = "Charlie";// Actvar result = foo.IsValid;// AssertAssert.IsTrue(result);}Unit of code we’re testingExpectations for our codeSingle assert, single outcome for test
Tips for writing good unit testsEach test should isolate a single unit of codeYou usually don’t want to have more than one or two asserts per test.
If you have several assertions in your tests, you are probably testing more than one thing, and could break it out into more than one test.Use “Arrange, Act, Assert” pattern to help keep your tests clean and simpleVerbose test method names can help you keep track of exactly what expectations you’re testing for
ImplementNow, we write the code to satisfy our test’s expectationspublic class Foo{public string Name { get; set; }    public bool IsValid    {get { return !string.IsNullOrEmpty(Name); }    }}
Test AgainAfter implementing the test case’s requirements in our code, we run the test again.It should pass this time.Move on to the next test case.
Unit Tests vs Integration TestsIntegration Tests incorporate outside elements into testing (e.g. – databases, web services, etc).Unit Tests should be designed to completely isolate your code from everything else.Both are VERY valuable. If you can, do both.
Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.public classFooController{private readonlyIFooRepository repository;public FooController() : this(newArenaFooRepository()) { }public FooController(IFooRepository repository)    {this.repository = repository;    }}
Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.public interface IFooRepository{FooGetFooByID(int id);IEnumerable<Foo>GetFooList();void Create(Foofoo);void Delete(Foofoo);void Save();}
Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.// Called from test code// Pass fake repository class to simulate database// Implements IFooRepositoryvarcontroller = newFooController(newFakeFooRepository());// Called from production code// Default constructor uses ArenaFooRepository object that knows about Arena DBvar controller = newFooController();
Types of Fake ObjectsStubA simple fake object you could write by hand. Intended to fake a component (e.g. – act as a database/repository substitute).Intended to be very simple.MockOften generated by a framework like Rhino Mocks or Moq.More robust than Stubs in that they can track what pieces of code from the object they’re faking are being used.Suited well to faking more complex object structures (e.g. -  HttpContext Request/Response).
But why go to all that trouble?This approach allows us to test our code more thoroughly. We can test application components and layers independently from each other.Test data access code (integration tests)Test entities/domain layer (unit tests)Test business/application logic layer (unit tests)

More Related Content

PPTX
Tdd & unit test
PPTX
Python Programming Essentials - M21 - Exception Handling
PPT
Automated Unit Testing
ODP
Python unit testing
PPTX
Python Programming Essentials - M39 - Unit Testing
PPTX
Refactoring
PDF
Modern Python Testing
PDF
Unit testing, principles
Tdd & unit test
Python Programming Essentials - M21 - Exception Handling
Automated Unit Testing
Python unit testing
Python Programming Essentials - M39 - Unit Testing
Refactoring
Modern Python Testing
Unit testing, principles

What's hot (20)

PPT
JMockit
PDF
Writing good unit test
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PDF
Exception Handling in Python - Rik van Achterberg & Tim Muller
PDF
Python exception handling
PDF
Auto testing!
PPTX
Unit Testing in Java
PPTX
Mockito vs JMockit, battle of the mocking frameworks
ODP
Automated testing in Python and beyond
 
PPT
Xp Day 080506 Unit Tests And Mocks
PPS
Coding Best Practices
PDF
C++ Unit Test with Google Testing Framework
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
ODT
Testing in-python-and-pytest-framework
PPTX
Refactoring legacy code driven by tests - ENG
PDF
Unit testing legacy code
PPTX
unittest in 5 minutes
PPT
How to test models using php unit testing framework?
PPT
20111018 boost and gtest
PPS
Why Unit Testingl
JMockit
Writing good unit test
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling in Python - Rik van Achterberg & Tim Muller
Python exception handling
Auto testing!
Unit Testing in Java
Mockito vs JMockit, battle of the mocking frameworks
Automated testing in Python and beyond
 
Xp Day 080506 Unit Tests And Mocks
Coding Best Practices
C++ Unit Test with Google Testing Framework
Mastering Mock Objects - Advanced Unit Testing for Java
Testing in-python-and-pytest-framework
Refactoring legacy code driven by tests - ENG
Unit testing legacy code
unittest in 5 minutes
How to test models using php unit testing framework?
20111018 boost and gtest
Why Unit Testingl
Ad

Viewers also liked (7)

PPTX
Rc2010 mef
PPTX
Unit testing concurrent code
PDF
Fission rate and_time_of_higly_excited_nuclei
PPTX
Rc2010 alt architecture
PDF
Unit testing basic
PDF
Report_Honda
PDF
Study: The Future of VR, AR and Self-Driving Cars
Rc2010 mef
Unit testing concurrent code
Fission rate and_time_of_higly_excited_nuclei
Rc2010 alt architecture
Unit testing basic
Report_Honda
Study: The Future of VR, AR and Self-Driving Cars
Ad

Similar to Rc2010 tdd (20)

PDF
Unit testing - A&BP CC
PPTX
PHPUnit: from zero to hero
PPT
Unit testing php-unit - phing - selenium_v2
PPT
Testing And Drupal
PPT
Ef Poco And Unit Testing
PDF
Fighting Fear-Driven-Development With PHPUnit
DOCX
Test Driven Development
PPT
Test Driven Development with PHPUnit
PPT
Testing Software Engineering systems end to end
PPTX
Unit tests & TDD
PPT
Stopping the Rot - Putting Legacy C++ Under Test
PPTX
Testing with VS2010 - A Bugs Life
PPTX
Unit Testing in .NET Core 7.0 with XUnit.pptx
PPT
Unit testing
PPT
TDD And Refactoring
PPS
JUnit Presentation
PPS
J unit presentation
PPTX
Tdd is not about testing (OOP)
PPTX
Building unit tests correctly with visual studio 2013
PPTX
JUnit Test Case With Processminer modules.pptx
Unit testing - A&BP CC
PHPUnit: from zero to hero
Unit testing php-unit - phing - selenium_v2
Testing And Drupal
Ef Poco And Unit Testing
Fighting Fear-Driven-Development With PHPUnit
Test Driven Development
Test Driven Development with PHPUnit
Testing Software Engineering systems end to end
Unit tests & TDD
Stopping the Rot - Putting Legacy C++ Under Test
Testing with VS2010 - A Bugs Life
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit testing
TDD And Refactoring
JUnit Presentation
J unit presentation
Tdd is not about testing (OOP)
Building unit tests correctly with visual studio 2013
JUnit Test Case With Processminer modules.pptx

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
sap open course for s4hana steps from ECC to s4
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Programs and apps: productivity, graphics, security and other tools
Digital-Transformation-Roadmap-for-Companies.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Big Data Technologies - Introduction.pptx

Rc2010 tdd

  • 1. Test Driven DevelopmentArrange, Act, Assert… AwesomeJason OffuttSoftware EngineerCentral Christian ChurchEmail: jason.offutt@cccev.comTwitter: @JasonOffutt #RefreshCache
  • 2. What is TDD?It’s a development methodologyWrite automated test cases to define what your code should be doing
  • 3. Write/Refactor code to satisfy test requirementsHow does it work?Write test case firstRun test (should fail)Write/Refactor code to satisfy test expectationsRun test again (should pass)???Profit
  • 4. How does it work?To run these automated tests, we need a test framework.MS TestMicrosoft’s testing frameworkAble to run tests from within Visual Studio’s GUIComes out of the box with Visual Studio (Professional or higher)NUnitSimpler/Cleaner syntax than MS TestComes with it’s own client to run tests, just point it at an assemblyFree to download and use3rd party tools like ReSharper allow NUnit tests to be executed directly in Visual Studio
  • 5. Test FirstThe goal is to write test cases to define expectations on how our code should behave.The result is that you end up with code that behaves in a predictable manner.In the end, you’ll have an entire suite of tests to prove your code works “correctly”.The first time we run a test, it should fail. We haven’t written any implementation to satisfy the test’s requirements yet.
  • 6. What does a test look like?[Test]public voidIsValid_Should_Return_True_When_Foo_Has_Name(){// Arrangevar foo = new Foo();foo.Name = "Charlie";// Actvar result = foo.IsValid;// AssertAssert.IsTrue(result);}
  • 7. What does a test look like?[Test]public voidIsValid_Should_Return_True_When_Foo_Has_Name(){// Arrangevar foo = new Foo();foo.Name = "Charlie";// Actvar result = foo.IsValid;// AssertAssert.IsTrue(result);}Unit of code we’re testingExpectations for our codeSingle assert, single outcome for test
  • 8. Tips for writing good unit testsEach test should isolate a single unit of codeYou usually don’t want to have more than one or two asserts per test.
  • 9. If you have several assertions in your tests, you are probably testing more than one thing, and could break it out into more than one test.Use “Arrange, Act, Assert” pattern to help keep your tests clean and simpleVerbose test method names can help you keep track of exactly what expectations you’re testing for
  • 10. ImplementNow, we write the code to satisfy our test’s expectationspublic class Foo{public string Name { get; set; } public bool IsValid {get { return !string.IsNullOrEmpty(Name); } }}
  • 11. Test AgainAfter implementing the test case’s requirements in our code, we run the test again.It should pass this time.Move on to the next test case.
  • 12. Unit Tests vs Integration TestsIntegration Tests incorporate outside elements into testing (e.g. – databases, web services, etc).Unit Tests should be designed to completely isolate your code from everything else.Both are VERY valuable. If you can, do both.
  • 13. Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.public classFooController{private readonlyIFooRepository repository;public FooController() : this(newArenaFooRepository()) { }public FooController(IFooRepository repository) {this.repository = repository; }}
  • 14. Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.public interface IFooRepository{FooGetFooByID(int id);IEnumerable<Foo>GetFooList();void Create(Foofoo);void Delete(Foofoo);void Save();}
  • 15. Keeping Unit Tests CleanTo isolate our code, use Dependency Inversion to create a “seam” so we can inject a fake object.// Called from test code// Pass fake repository class to simulate database// Implements IFooRepositoryvarcontroller = newFooController(newFakeFooRepository());// Called from production code// Default constructor uses ArenaFooRepository object that knows about Arena DBvar controller = newFooController();
  • 16. Types of Fake ObjectsStubA simple fake object you could write by hand. Intended to fake a component (e.g. – act as a database/repository substitute).Intended to be very simple.MockOften generated by a framework like Rhino Mocks or Moq.More robust than Stubs in that they can track what pieces of code from the object they’re faking are being used.Suited well to faking more complex object structures (e.g. - HttpContext Request/Response).
  • 17. But why go to all that trouble?This approach allows us to test our code more thoroughly. We can test application components and layers independently from each other.Test data access code (integration tests)Test entities/domain layer (unit tests)Test business/application logic layer (unit tests)