SlideShare uma empresa Scribd logo
1 de 70
PRINCIPLES AND PATTERNS FOR
TEST DRIVEN DEVELOPMENT
Author: Stephen Fuqua
Last Revised: May 2014
All content by the author or from public domain sources unless otherwise noted
PART 1
Testing – Not Just for QA
Benefits: Risk Reduction
• Safely refactor - regression
Benefits: Risk Reduction
• Safely refactor - regression
• Think about "edge cases"
Benefits: Risk Reduction
• Safely refactor - regression
• Think about "edge cases"
• Duh - prove that the software works
Benefits: Better Design
• Safely refactor - evolve
Benefits: Better Design
• Safely refactor - evolve
• Focus on clean, modular code. Key patterns for
easier testing:
• Single Responsibility Principle
• Dependency Injection
• Adapter
Benefits: Better Design
• Safely refactor - evolve
• Focus on clean, modular code. Key patterns for
easier testing:
• Single Responsibility Principle
• Dependency Injection
• Adapter
• Concentrate on simple inputs and outputs
Benefits: Better Design
• Safely refactor - evolve
• Focus on clean, modular code. Key patterns for
easier testing:
• Single Responsibility Principle
• Dependency Injection
• Adapter
• Concentrate on simple inputs and outputs
• Express requirements via tests
Four Types
Scope Unit Functional Acceptance Performance
Method x x
Class x x
Includes I/O x x x
Entire
Application
x x
Entire System x
Where We Are Going
• Thinking About Testing
• Test Driven Development (TDD)
• Legacy TDD
• Obstacles
https://www.flickr.com/photos/wsdot/
PART 2
Thinking About Testing
Approaching Testing
• Write expressively, with intent-revealing names
Approaching Testing
• Write expressively, with intent-revealing names
• Express a business need
Approaching Testing
• Write expressively, with intent-revealing names
• Express a business need
• Concentrate on inputs and outputs for a system
under test
Approaching Testing
• Write expressively, with intent-revealing names
• Express a business need
• Concentrate on inputs and outputs for a system
under test
• // Prepare Input
// Call the system under test
// Evaluate outputs
Given
When
Then
Approaching Testing
• Write expressively, with intent-revealing names
• Express a business need
• Concentrate on inputs and outputs for a system
under test
• // Prepare Input
// Call the system under test
// Evaluate outputs
• Given
When
Then
User Stories
• Write (or get) user stories.
• More useful for Behavior Driven Development,
but still helpful in thinking about unit and
functional tests
User Stories
• Write (or get) user stories.
• More useful for Behavior Driven Development,
but still helpful in thinking about unit and
functional tests
Negative Testing
• Unexpected input
• Null values
• Overflows
• Expected messages
• Exception handling
• Check the logs
Isolation
• Unit: isolated from I/O, web
services, etc.
Isolation
• Unit: isolated from I/O, web
services, etc.
• Functional: connect to just one
outside source
Isolation
• Unit: isolated from I/O, web
services, etc.
• Functional: connect to just one
outside source
• Avoid interactions from other
systems and test
Isolation
• Unit: isolated from I/O, web
services, etc.
• Functional: connect to just one
outside source
• Avoid interactions from other
systems and test
• Setup a self-contained system
Three Essential OO Patterns
• Can’t effectively isolate a method or class
without…
Three Essential OO Patterns
• Can’t effectively isolate a method or class
without…
• Single Responsibility Principle (SRP)
Three Essential OO Patterns
• Can’t effectively isolate a method or class
without…
• Single Responsibility Principle (SRP)
• Dependency Injection (DI)
• Constructor, Property, Method, even
Static Delegate Injection
Three Essential OO Patterns
• Can’t effectively isolate a method or class
without…
• Single Responsibility Principle (SRP)
• Dependency Injection (DI)
• Constructor, Property, Method, even
Static Delegate Injection
• Adapter
PART 3
Test Driven Development
Essential Formula
1. Write a test that fails
Essential Formula
1. Write a test that fails
2. Write the code that makes it pass
Essential Formula
1. Write a test that fails
2. Write the code that makes it pass
3. Clean up the code
MSTest
using System;
using
Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Reggie.UI.Tests
{
[TestClass]
public class UnitTest1
{
[ClassInitialize]
public static void
ClassInitializer(TestContext context)
{
// Note that it is static.
// Runs once per class.
}
[TestInitialize]
public void TestInitializer()
{
// Runs once before each test.
// Runs after constructor.
}
[TestMethod]
public void TestMethod1()
{
}
[TestCleanup]
public void TestCleanuper()
{
// Runs once after each test.
}
[ClassCleanup]
public static void ClassCleanuper()
{
// Again static.
// Runs after all tests complete.
}
}
}
Assertions
• Verify the results after running the system:
Assert.<something>(expected, actual, message)
• Some frameworks reverse (actual, expected)
• Message – clear enough to know which failed
• Common:
o Assert.AreEqual
o Assert.IsNull
o Assert.IsNotNull
o Assert.AreSame
o Assert.IsTrue
o Assert.IsFalse
More Verification
• Many frameworks have an attribute like
[ExpectedException(typeof(SomeException))]
• Alternately, catch exceptions and inspect
details.
• Caught the wrong exception?
Assert.Fail(“oops looks like I caught an
” + typeof(actual).ToString());
Test Runner
Isolation Patterns
• Fake – light-weight replacement for expected
input or dependency
Isolation Patterns
• Fake – light-weight replacement for expected
input or dependency
• Stub – (partially complete) implementation of
an input type
Isolation Patterns
• Fake – light-weight replacement for expected
input or dependency
• Stub – (partially complete) implementation of
an input type
• Mock – replacement for input dependency,
coded to expect specific behavior (output)
Isolation Patterns
• Fake – light-weight replacement for expected
input or dependency
• Stub – (partially complete) implementation of
an input type
• Mock – replacement for input dependency,
coded to expect specific behavior (output)
• Test-specific subclass – used to break
encapsulation or provide a fake
Mocking
• Could be handwritten
• Typically use a framework: Moq, jMock, Sinon
• Specify only expected behavior: in Moq,
MockBehavior.Strict
• Criticism: over-specifying
Mock Example
var mocks = new MockRepository(MockBehavior.Strict);
var filesys = mocks.Create<IFileAdapter>();
var system = new ReggieXmlFile(filesys.Object);
// Prepare input
var input = new ReggieSession()
{
RegularExpressionPattern = "323",
SampleText = "46346kljlk"
};
string fileToOpen = "c:thisfile.reggie";
// Setup expectations
var extension = ReggieXmlFile.ReggieExtension;
var filter = ReggieXmlFile.ReggieFilter;
filesys.Setup(x => x.OpenFileSaveDialogBox(
It.Is<string>(y => y == extension),
It.Is<string>(y => y == filter)))
.Returns(fileToOpen);
filesys.Setup(x =>
x.SerializeXmlFile<ReggieSession>(
It.IsAny<ReggieSession[]>(),
It.IsAny<string>()))
.Callback(
(ReggieSession[] iSession, string iFile) =>
{
Assert.AreSame(input,
iSession.FirstOrDefault(), "session");
Assert.AreEqual(fileToOpen, iFile, "file
name");
});
// Call the system under test
var actual = system.Save(input);
// Evaluate output
Assert.IsTrue(actual, "wrong response");
mocks.VerifyAll();
Mock Example
var mocks = new MockRepository(MockBehavior.Strict);
var filesys = mocks.Create<IFileAdapter>();
var system = new ReggieXmlFile(filesys.Object);
// Prepare input
var input = new ReggieSession()
{
RegularExpressionPattern = "323",
SampleText = "46346kljlk"
};
string fileToOpen = "c:thisfile.reggie";
// Setup expectations
var extension = ReggieXmlFile.ReggieExtension;
var filter = ReggieXmlFile.ReggieFilter;
filesys.Setup(x => x.OpenFileSaveDialogBox(
It.Is<string>(y => y == extension),
It.Is<string>(y => y == filter)))
.Returns(fileToOpen);
filesys.Setup(x =>
x.SerializeXmlFile<ReggieSession>(
It.IsAny<ReggieSession[]>(),
It.IsAny<string>()))
.Callback(
(ReggieSession[] iSession, string iFile) =>
{
Assert.AreSame(input,
iSession.FirstOrDefault(), "session");
Assert.AreEqual(fileToOpen, iFile, "file
name");
});
// Call the system under test
var actual = system.Save(input);
// Evaluate output
Assert.IsTrue(actual, "wrong response");
mocks.VerifyAll();
Intent-Revealing Names
MockRepository mocks = new
MockRepository(MockBehavior.Strict);
Mock<IFileAdapter> filesys;
[TestInitialize]
public void TestInitializer()
{
filesys = mocks.Create<IFileAdapter>();
}
[TestMethod]
public void SaveSessionToXmlFile2()
{
var input = givenASessionObjectStoring(
pattern: "323",
text: "46346kljlk");
string outputFile =
"c:thisfile.reggie";
expectToOpenTheSaveFileDialogBox(outputFile);
expectToSerializeXmlRepresentingThisSession(inp
ut, outputFile);
var system = givenTheSystemUnderTest();
var actual = system.Save(input);
thenTheResponseShouldBe(actual, true);
}
[TestCleanup]
public void TestCleanup()
{
mocks.VerifyAll();
}
Functional Integration Isolation
• Essential: start with a clean slate
• Use a sandbox database on localhost
• Delete and re-create sample files / records
• Launch a service in a separate thread
Code Coverage
Code Coverage
Common Test Smells
• Assertion Roulette
• Interacting Tests
• Conditional Test Logic
• Test Code duplication
• Obscure Test
from xUnit Test Patterns
PART 4
Legacy Testing
Modified Formula
1. Write a test that passes
2. Write a test that fails
3. Write the code that makes it pass
4. Clean up the code
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
• Lazy-load for property injection
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
• Lazy-load for property injection
• Split a method or class into multiple
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
• Lazy-load for property injection
• Split a method or class into multiple
• Rethink class variables – pass as arguments instead?
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
• Lazy-load for property injection
• Split a method or class into multiple
• Rethink class variables – pass as arguments instead?
• Test-specific sub-class to set protected variables
Refactoring
• Often too hard to test - insufficiently isolated
• Slowly refactor, one step at a time
• Introduce an interface for constructor injection
• Lazy-load for property injection
• Split a method or class into multiple
• Rethink class variables – pass as arguments instead?
• Test-specific sub-class to set protected variables
• Or: brand new code, called from old methods
Fakes and Shims
• Dangerous! Method of last resort!
• Hard-codes dependencies: external resources,
MSDN Premium/Ultimate
using (ShimsContext.Create())
{
Fakes.ShimReggieXmlFile.AllInstances.Retrieve
= (ReggieXmlFile inputFile) =>
{
return new Reggie.BLL.Entities.ReggieSession();
};
// Now I can test SomeOtherClass that calls the Retrieve method
}
Suggestions
• Legacy code deserves tests
• Analyze code coverage for each release,
ensuring it goes up
• No emergency maintenance without Green-
Red-Green-(Refactor) approach
PART 5
Obstacles
Learning Curve
<discussion>
Learning Curve – Additional Tips
• Resources at end of the presentation
• Study tests in open source projects, e.g.
reggie.codeplex.com
• Pair programming
Sufficient Time
<discussion>
Sufficient Time – Additional Tips
• Management must commit
• Double your estimates – then retrospectively
check and see if that was “good enough”
Legacy Code
<discussion>
Legacy Code – Additional Tips
• What’s the risk tolerance? If high enough,
might not be worth it
• Might have better success with BDD than TDD,
since BDD typically tests the entire application
• Targeted use of TDD – special cases,
enhancements, bug fixes
PART 6
Resources
Books
• Clean Code, Robert C. Martin
• xUnit Test Patterns, Gerard Meszaros
• Growing Object-Oriented Software, Guided by
Tests, Steve Freeman and Nat Pryce
• Agile Testing, A Practical Guide for Testers and
Teams, Lisa Crispin and Janet Gregory
• Can’t vouch for personally, but looks promising:
Working with Legacy Code, by Michael C.
Feathers
On The Web
• xUnit Test Patterns (light version of the book)
• Red-Green-Refactor (the original?)
• Martin Fowler on Mocks Aren't Stubs
• TDD when up to your neck in Legacy Code
• That Pesky MSTest Execution Ordering…
Author’s Blog Posts
• Making Mockery of Extension Methods
• TACKLE: Be Test-Driven
• Dependency Injection with Entity Framework
• Review: Growing Object-Oriented Software, Guided By Tests
• Breaking Down a Unit Test from "Reggie" That Uses MoQ
• Moles: No Longer Fit for Unit Tests
• Breaking My Moles Habit, With MoQ
• Unit vs. Integration Tests When Querying Nullable Columns
• TDD - Scenario for Red, Green, Refactor
• Sub classing for automated testing
• Unit Testing - Code Coverage and Separation of Layers

Mais conteúdo relacionado

Mais procurados

ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
Intro to react native
Intro to react nativeIntro to react native
Intro to react nativeModusJesus
 
Installing Python 2.7 in Windows
Installing Python 2.7 in WindowsInstalling Python 2.7 in Windows
Installing Python 2.7 in WindowsSiva Arunachalam
 
Flutter App Development Building Cross-Platform Apps.pdf
Flutter App Development Building Cross-Platform Apps.pdfFlutter App Development Building Cross-Platform Apps.pdf
Flutter App Development Building Cross-Platform Apps.pdfShiv Technolabs Pvt. Ltd.
 
Pairwise testing - Strategic test case design
Pairwise testing - Strategic test case designPairwise testing - Strategic test case design
Pairwise testing - Strategic test case designXBOSoft
 
ITIL, Release Management and Automation
ITIL, Release Management and AutomationITIL, Release Management and Automation
ITIL, Release Management and AutomationIBM UrbanCode Products
 
エムスリーのQAチームが目指すもの
エムスリーのQAチームが目指すものエムスリーのQAチームが目指すもの
エムスリーのQAチームが目指すものYuki Shiromoto
 
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...Edureka!
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patternsLilia Sfaxi
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycleDina Hanbazazah
 
WebSphere Application Server JBoss TCO analysis
WebSphere Application Server JBoss TCO analysisWebSphere Application Server JBoss TCO analysis
WebSphere Application Server JBoss TCO analysisShetal Patel
 
われわれはなぜアジャイルに向かうのか
われわれはなぜアジャイルに向かうのかわれわれはなぜアジャイルに向かうのか
われわれはなぜアジャイルに向かうのかtoshihiro ichitani
 
Lesson 4...Bug Life Cycle
Lesson 4...Bug Life CycleLesson 4...Bug Life Cycle
Lesson 4...Bug Life Cyclebhushan Nehete
 
Thin Controllers Fat Models - How to Write Better Code
Thin Controllers Fat Models - How to Write Better CodeThin Controllers Fat Models - How to Write Better Code
Thin Controllers Fat Models - How to Write Better CodeDr. Syed Hassan Amin
 

Mais procurados (20)

ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Intro to react native
Intro to react nativeIntro to react native
Intro to react native
 
Installing Python 2.7 in Windows
Installing Python 2.7 in WindowsInstalling Python 2.7 in Windows
Installing Python 2.7 in Windows
 
React Native Workshop
React Native WorkshopReact Native Workshop
React Native Workshop
 
Vmodel
VmodelVmodel
Vmodel
 
Flutter App Development Building Cross-Platform Apps.pdf
Flutter App Development Building Cross-Platform Apps.pdfFlutter App Development Building Cross-Platform Apps.pdf
Flutter App Development Building Cross-Platform Apps.pdf
 
Pairwise testing - Strategic test case design
Pairwise testing - Strategic test case designPairwise testing - Strategic test case design
Pairwise testing - Strategic test case design
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React Native
 
ITIL, Release Management and Automation
ITIL, Release Management and AutomationITIL, Release Management and Automation
ITIL, Release Management and Automation
 
Junit
JunitJunit
Junit
 
エムスリーのQAチームが目指すもの
エムスリーのQAチームが目指すものエムスリーのQAチームが目指すもの
エムスリーのQAチームが目指すもの
 
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
 
WebSphere Application Server JBoss TCO analysis
WebSphere Application Server JBoss TCO analysisWebSphere Application Server JBoss TCO analysis
WebSphere Application Server JBoss TCO analysis
 
STLC
STLCSTLC
STLC
 
われわれはなぜアジャイルに向かうのか
われわれはなぜアジャイルに向かうのかわれわれはなぜアジャイルに向かうのか
われわれはなぜアジャイルに向かうのか
 
Introducing DevOps
Introducing DevOpsIntroducing DevOps
Introducing DevOps
 
Lesson 4...Bug Life Cycle
Lesson 4...Bug Life CycleLesson 4...Bug Life Cycle
Lesson 4...Bug Life Cycle
 
Thin Controllers Fat Models - How to Write Better Code
Thin Controllers Fat Models - How to Write Better CodeThin Controllers Fat Models - How to Write Better Code
Thin Controllers Fat Models - How to Write Better Code
 

Destaque

Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Moq Presentation
Moq PresentationMoq Presentation
Moq PresentationLynxStar
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Shallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDShallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDfabiopereirame
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Sequential file programming patterns and performance with .net
Sequential  file programming patterns and performance with .netSequential  file programming patterns and performance with .net
Sequential file programming patterns and performance with .netMichael Pavlovsky
 
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013Justin Richer
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Test Driven Development for Embedded C
Test Driven Development for Embedded CTest Driven Development for Embedded C
Test Driven Development for Embedded CJames Grenning
 
Introduction to the Emerging JSON-Based Identity and Security Protocols
Introduction to the Emerging JSON-Based Identity and Security ProtocolsIntroduction to the Emerging JSON-Based Identity and Security Protocols
Introduction to the Emerging JSON-Based Identity and Security ProtocolsBrian Campbell
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Jessica Mauerhan
 

Destaque (20)

TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
TDD, BDD, RSpec
TDD, BDD, RSpecTDD, BDD, RSpec
TDD, BDD, RSpec
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Moq Presentation
Moq PresentationMoq Presentation
Moq Presentation
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Shallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDDShallow Depth of Tests Scallable BDD and TDD
Shallow Depth of Tests Scallable BDD and TDD
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Sequential file programming patterns and performance with .net
Sequential  file programming patterns and performance with .netSequential  file programming patterns and performance with .net
Sequential file programming patterns and performance with .net
 
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013
Auth in the extended enterprise - Keynote for MIT Legal Hack A Thon 2013
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Test Driven Development for Embedded C
Test Driven Development for Embedded CTest Driven Development for Embedded C
Test Driven Development for Embedded C
 
Introduction to the Emerging JSON-Based Identity and Security Protocols
Introduction to the Emerging JSON-Based Identity and Security ProtocolsIntroduction to the Emerging JSON-Based Identity and Security Protocols
Introduction to the Emerging JSON-Based Identity and Security Protocols
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!
 
Introduction to OAuth2.0
Introduction to OAuth2.0Introduction to OAuth2.0
Introduction to OAuth2.0
 

Semelhante a Principles and patterns for test driven development

Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 
Tests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and StrategyTests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and StrategySalesforce Developers
 
Unit testing in Force.com platform
Unit testing in Force.com platformUnit testing in Force.com platform
Unit testing in Force.com platformChamil Madusanka
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptxskknowledge
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsSteven Li
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherencearagozin
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayJordi Pradel
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 

Semelhante a Principles and patterns for test driven development (20)

Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Tests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and StrategyTests and Testability: Apex Structure and Strategy
Tests and Testability: Apex Structure and Strategy
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Unit testing in Force.com platform
Unit testing in Force.com platformUnit testing in Force.com platform
Unit testing in Force.com platform
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
Unit testing
Unit testingUnit testing
Unit testing
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementations
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherence
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy Way
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 

Mais de Stephen Fuqua

Spiritual laws and admonitions for sustainable living
Spiritual laws and admonitions for sustainable livingSpiritual laws and admonitions for sustainable living
Spiritual laws and admonitions for sustainable livingStephen Fuqua
 
Environmental ethics and behavior deriving from writings of abdul baha
Environmental ethics and behavior deriving from writings of abdul bahaEnvironmental ethics and behavior deriving from writings of abdul baha
Environmental ethics and behavior deriving from writings of abdul bahaStephen Fuqua
 
Faithful Call to #ActOnClimate
Faithful Call to #ActOnClimateFaithful Call to #ActOnClimate
Faithful Call to #ActOnClimateStephen Fuqua
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)Moral Imperatives for Climate Action from a Baha'i Perspective (v3)
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)Stephen Fuqua
 
Contributing to the Discourses of Society
Contributing to the Discourses of SocietyContributing to the Discourses of Society
Contributing to the Discourses of SocietyStephen Fuqua
 

Mais de Stephen Fuqua (6)

Spiritual laws and admonitions for sustainable living
Spiritual laws and admonitions for sustainable livingSpiritual laws and admonitions for sustainable living
Spiritual laws and admonitions for sustainable living
 
Environmental ethics and behavior deriving from writings of abdul baha
Environmental ethics and behavior deriving from writings of abdul bahaEnvironmental ethics and behavior deriving from writings of abdul baha
Environmental ethics and behavior deriving from writings of abdul baha
 
Faithful Call to #ActOnClimate
Faithful Call to #ActOnClimateFaithful Call to #ActOnClimate
Faithful Call to #ActOnClimate
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)Moral Imperatives for Climate Action from a Baha'i Perspective (v3)
Moral Imperatives for Climate Action from a Baha'i Perspective (v3)
 
Contributing to the Discourses of Society
Contributing to the Discourses of SocietyContributing to the Discourses of Society
Contributing to the Discourses of Society
 

Último

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Último (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Principles and patterns for test driven development

  • 1. PRINCIPLES AND PATTERNS FOR TEST DRIVEN DEVELOPMENT Author: Stephen Fuqua Last Revised: May 2014 All content by the author or from public domain sources unless otherwise noted
  • 2. PART 1 Testing – Not Just for QA
  • 3. Benefits: Risk Reduction • Safely refactor - regression
  • 4. Benefits: Risk Reduction • Safely refactor - regression • Think about "edge cases"
  • 5. Benefits: Risk Reduction • Safely refactor - regression • Think about "edge cases" • Duh - prove that the software works
  • 6. Benefits: Better Design • Safely refactor - evolve
  • 7. Benefits: Better Design • Safely refactor - evolve • Focus on clean, modular code. Key patterns for easier testing: • Single Responsibility Principle • Dependency Injection • Adapter
  • 8. Benefits: Better Design • Safely refactor - evolve • Focus on clean, modular code. Key patterns for easier testing: • Single Responsibility Principle • Dependency Injection • Adapter • Concentrate on simple inputs and outputs
  • 9. Benefits: Better Design • Safely refactor - evolve • Focus on clean, modular code. Key patterns for easier testing: • Single Responsibility Principle • Dependency Injection • Adapter • Concentrate on simple inputs and outputs • Express requirements via tests
  • 10. Four Types Scope Unit Functional Acceptance Performance Method x x Class x x Includes I/O x x x Entire Application x x Entire System x
  • 11. Where We Are Going • Thinking About Testing • Test Driven Development (TDD) • Legacy TDD • Obstacles https://www.flickr.com/photos/wsdot/
  • 13. Approaching Testing • Write expressively, with intent-revealing names
  • 14. Approaching Testing • Write expressively, with intent-revealing names • Express a business need
  • 15. Approaching Testing • Write expressively, with intent-revealing names • Express a business need • Concentrate on inputs and outputs for a system under test
  • 16. Approaching Testing • Write expressively, with intent-revealing names • Express a business need • Concentrate on inputs and outputs for a system under test • // Prepare Input // Call the system under test // Evaluate outputs Given When Then
  • 17. Approaching Testing • Write expressively, with intent-revealing names • Express a business need • Concentrate on inputs and outputs for a system under test • // Prepare Input // Call the system under test // Evaluate outputs • Given When Then
  • 18. User Stories • Write (or get) user stories. • More useful for Behavior Driven Development, but still helpful in thinking about unit and functional tests
  • 19. User Stories • Write (or get) user stories. • More useful for Behavior Driven Development, but still helpful in thinking about unit and functional tests
  • 20. Negative Testing • Unexpected input • Null values • Overflows • Expected messages • Exception handling • Check the logs
  • 21. Isolation • Unit: isolated from I/O, web services, etc.
  • 22. Isolation • Unit: isolated from I/O, web services, etc. • Functional: connect to just one outside source
  • 23. Isolation • Unit: isolated from I/O, web services, etc. • Functional: connect to just one outside source • Avoid interactions from other systems and test
  • 24. Isolation • Unit: isolated from I/O, web services, etc. • Functional: connect to just one outside source • Avoid interactions from other systems and test • Setup a self-contained system
  • 25. Three Essential OO Patterns • Can’t effectively isolate a method or class without…
  • 26. Three Essential OO Patterns • Can’t effectively isolate a method or class without… • Single Responsibility Principle (SRP)
  • 27. Three Essential OO Patterns • Can’t effectively isolate a method or class without… • Single Responsibility Principle (SRP) • Dependency Injection (DI) • Constructor, Property, Method, even Static Delegate Injection
  • 28. Three Essential OO Patterns • Can’t effectively isolate a method or class without… • Single Responsibility Principle (SRP) • Dependency Injection (DI) • Constructor, Property, Method, even Static Delegate Injection • Adapter
  • 29. PART 3 Test Driven Development
  • 30. Essential Formula 1. Write a test that fails
  • 31. Essential Formula 1. Write a test that fails 2. Write the code that makes it pass
  • 32. Essential Formula 1. Write a test that fails 2. Write the code that makes it pass 3. Clean up the code
  • 33. MSTest using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Reggie.UI.Tests { [TestClass] public class UnitTest1 { [ClassInitialize] public static void ClassInitializer(TestContext context) { // Note that it is static. // Runs once per class. } [TestInitialize] public void TestInitializer() { // Runs once before each test. // Runs after constructor. } [TestMethod] public void TestMethod1() { } [TestCleanup] public void TestCleanuper() { // Runs once after each test. } [ClassCleanup] public static void ClassCleanuper() { // Again static. // Runs after all tests complete. } } }
  • 34. Assertions • Verify the results after running the system: Assert.<something>(expected, actual, message) • Some frameworks reverse (actual, expected) • Message – clear enough to know which failed • Common: o Assert.AreEqual o Assert.IsNull o Assert.IsNotNull o Assert.AreSame o Assert.IsTrue o Assert.IsFalse
  • 35. More Verification • Many frameworks have an attribute like [ExpectedException(typeof(SomeException))] • Alternately, catch exceptions and inspect details. • Caught the wrong exception? Assert.Fail(“oops looks like I caught an ” + typeof(actual).ToString());
  • 37. Isolation Patterns • Fake – light-weight replacement for expected input or dependency
  • 38. Isolation Patterns • Fake – light-weight replacement for expected input or dependency • Stub – (partially complete) implementation of an input type
  • 39. Isolation Patterns • Fake – light-weight replacement for expected input or dependency • Stub – (partially complete) implementation of an input type • Mock – replacement for input dependency, coded to expect specific behavior (output)
  • 40. Isolation Patterns • Fake – light-weight replacement for expected input or dependency • Stub – (partially complete) implementation of an input type • Mock – replacement for input dependency, coded to expect specific behavior (output) • Test-specific subclass – used to break encapsulation or provide a fake
  • 41. Mocking • Could be handwritten • Typically use a framework: Moq, jMock, Sinon • Specify only expected behavior: in Moq, MockBehavior.Strict • Criticism: over-specifying
  • 42. Mock Example var mocks = new MockRepository(MockBehavior.Strict); var filesys = mocks.Create<IFileAdapter>(); var system = new ReggieXmlFile(filesys.Object); // Prepare input var input = new ReggieSession() { RegularExpressionPattern = "323", SampleText = "46346kljlk" }; string fileToOpen = "c:thisfile.reggie"; // Setup expectations var extension = ReggieXmlFile.ReggieExtension; var filter = ReggieXmlFile.ReggieFilter; filesys.Setup(x => x.OpenFileSaveDialogBox( It.Is<string>(y => y == extension), It.Is<string>(y => y == filter))) .Returns(fileToOpen); filesys.Setup(x => x.SerializeXmlFile<ReggieSession>( It.IsAny<ReggieSession[]>(), It.IsAny<string>())) .Callback( (ReggieSession[] iSession, string iFile) => { Assert.AreSame(input, iSession.FirstOrDefault(), "session"); Assert.AreEqual(fileToOpen, iFile, "file name"); }); // Call the system under test var actual = system.Save(input); // Evaluate output Assert.IsTrue(actual, "wrong response"); mocks.VerifyAll();
  • 43. Mock Example var mocks = new MockRepository(MockBehavior.Strict); var filesys = mocks.Create<IFileAdapter>(); var system = new ReggieXmlFile(filesys.Object); // Prepare input var input = new ReggieSession() { RegularExpressionPattern = "323", SampleText = "46346kljlk" }; string fileToOpen = "c:thisfile.reggie"; // Setup expectations var extension = ReggieXmlFile.ReggieExtension; var filter = ReggieXmlFile.ReggieFilter; filesys.Setup(x => x.OpenFileSaveDialogBox( It.Is<string>(y => y == extension), It.Is<string>(y => y == filter))) .Returns(fileToOpen); filesys.Setup(x => x.SerializeXmlFile<ReggieSession>( It.IsAny<ReggieSession[]>(), It.IsAny<string>())) .Callback( (ReggieSession[] iSession, string iFile) => { Assert.AreSame(input, iSession.FirstOrDefault(), "session"); Assert.AreEqual(fileToOpen, iFile, "file name"); }); // Call the system under test var actual = system.Save(input); // Evaluate output Assert.IsTrue(actual, "wrong response"); mocks.VerifyAll();
  • 44. Intent-Revealing Names MockRepository mocks = new MockRepository(MockBehavior.Strict); Mock<IFileAdapter> filesys; [TestInitialize] public void TestInitializer() { filesys = mocks.Create<IFileAdapter>(); } [TestMethod] public void SaveSessionToXmlFile2() { var input = givenASessionObjectStoring( pattern: "323", text: "46346kljlk"); string outputFile = "c:thisfile.reggie"; expectToOpenTheSaveFileDialogBox(outputFile); expectToSerializeXmlRepresentingThisSession(inp ut, outputFile); var system = givenTheSystemUnderTest(); var actual = system.Save(input); thenTheResponseShouldBe(actual, true); } [TestCleanup] public void TestCleanup() { mocks.VerifyAll(); }
  • 45. Functional Integration Isolation • Essential: start with a clean slate • Use a sandbox database on localhost • Delete and re-create sample files / records • Launch a service in a separate thread
  • 48. Common Test Smells • Assertion Roulette • Interacting Tests • Conditional Test Logic • Test Code duplication • Obscure Test from xUnit Test Patterns
  • 50. Modified Formula 1. Write a test that passes 2. Write a test that fails 3. Write the code that makes it pass 4. Clean up the code
  • 51. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time
  • 52. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection
  • 53. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection • Lazy-load for property injection
  • 54. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection • Lazy-load for property injection • Split a method or class into multiple
  • 55. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection • Lazy-load for property injection • Split a method or class into multiple • Rethink class variables – pass as arguments instead?
  • 56. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection • Lazy-load for property injection • Split a method or class into multiple • Rethink class variables – pass as arguments instead? • Test-specific sub-class to set protected variables
  • 57. Refactoring • Often too hard to test - insufficiently isolated • Slowly refactor, one step at a time • Introduce an interface for constructor injection • Lazy-load for property injection • Split a method or class into multiple • Rethink class variables – pass as arguments instead? • Test-specific sub-class to set protected variables • Or: brand new code, called from old methods
  • 58. Fakes and Shims • Dangerous! Method of last resort! • Hard-codes dependencies: external resources, MSDN Premium/Ultimate using (ShimsContext.Create()) { Fakes.ShimReggieXmlFile.AllInstances.Retrieve = (ReggieXmlFile inputFile) => { return new Reggie.BLL.Entities.ReggieSession(); }; // Now I can test SomeOtherClass that calls the Retrieve method }
  • 59. Suggestions • Legacy code deserves tests • Analyze code coverage for each release, ensuring it goes up • No emergency maintenance without Green- Red-Green-(Refactor) approach
  • 62. Learning Curve – Additional Tips • Resources at end of the presentation • Study tests in open source projects, e.g. reggie.codeplex.com • Pair programming
  • 64. Sufficient Time – Additional Tips • Management must commit • Double your estimates – then retrospectively check and see if that was “good enough”
  • 66. Legacy Code – Additional Tips • What’s the risk tolerance? If high enough, might not be worth it • Might have better success with BDD than TDD, since BDD typically tests the entire application • Targeted use of TDD – special cases, enhancements, bug fixes
  • 68. Books • Clean Code, Robert C. Martin • xUnit Test Patterns, Gerard Meszaros • Growing Object-Oriented Software, Guided by Tests, Steve Freeman and Nat Pryce • Agile Testing, A Practical Guide for Testers and Teams, Lisa Crispin and Janet Gregory • Can’t vouch for personally, but looks promising: Working with Legacy Code, by Michael C. Feathers
  • 69. On The Web • xUnit Test Patterns (light version of the book) • Red-Green-Refactor (the original?) • Martin Fowler on Mocks Aren't Stubs • TDD when up to your neck in Legacy Code • That Pesky MSTest Execution Ordering…
  • 70. Author’s Blog Posts • Making Mockery of Extension Methods • TACKLE: Be Test-Driven • Dependency Injection with Entity Framework • Review: Growing Object-Oriented Software, Guided By Tests • Breaking Down a Unit Test from "Reggie" That Uses MoQ • Moles: No Longer Fit for Unit Tests • Breaking My Moles Habit, With MoQ • Unit vs. Integration Tests When Querying Nullable Columns • TDD - Scenario for Red, Green, Refactor • Sub classing for automated testing • Unit Testing - Code Coverage and Separation of Layers

Notas do Editor

  1. Good opportunity for brief participation, defining these.