SlideShare una empresa de Scribd logo
1 de 14
A Better Way to Setup
Test Data
Poya Manouchehri
@PoyaManouchehri
poya.manouchehri@readify.net
http://askpoya.wordpress.com/
1. Intent is Unclear:
• What is 160?
• Is nationality important?
2. Test is Brittle:
• Changing the constructor will break many tests
[Test]
public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown()
{
// Arrange
var sarah = new Person("Sarah", "Smith", DateTime.Today.AddYears(-15), 160, "Australian");
// Act / Assert
Assert.Throws<InvalidOperationException>(() =>
sarah.AssignDriverLicense(DriverLicenseType.Automatic));
}
public static partial class ObjectMother
{
public static class Persons
{
public static Person FifteenYearOldSarah
{
get
{
return new Person("Sarah", "Smith", DateTime.Today.AddYears(-17), 160, "Australian");
}
}
public static Person BrazilianRafael
{
get
{
return new Person("Rafael", "Gomez", new DateTime(1985, 12 , 2), 177, “Brazilian")
}
}
}
}
Object Mother Pattern
[Test]
public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown()
{
var sarah = ObjectMother.Persons.FifteenYearOldSarah;
Assert.Throws<InvalidOperationException>(() =>
sarah.AssignDriverLicense(DriverLicenseType.Automatic));
}
Object Mother Pattern
var person = new PersonBuilder()
.WithName("Michael", "Jackson")
.BornOn(new DateTime(1958, 8, 29))
.WithHeight(175)
.WithNationality("American")
.WhoHasDriverLicense(DriverLicenseType.Truck)
.Build();
Builder Pattern
[Test]
public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown()
{
var person = new PersonBuilder()
.BornOn(DateTime.Today.AddYears(-15))
.Build();
Assert.Throws<InvalidOperationException>(() =>
person.AssignDriverLicense(DriverLicenseType.Automatic));
}
Builder Pattern
[Test]
public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown()
{
var person = ObjectMother.Persons.Sarah
.BornOn(DateTime.Today.AddYears(-15))
.Build();
Assert.Throws<InvalidOperationException>(() =>
person.AssignDriverLicense(DriverLicenseType.Automatic));
}
Builder Pattern
var people = PersonBuilder.CreateListOfSize(10)
.All().Do(p => p.WithNationality("Australian"))
.TheFirst(2).Do(p => p.BornOn(new DateTime(1980, 1, 1)))
.TheNext(3).Do(p => p.BornOn(new DateTime(1974, 10, 15)))
.Random(2).Do(p => p.WithHeight(180))
.BuildList<Person, PersonBuilder>();
Building Collections with NBuilder
var people = new[]
{
new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1980, 1, 1)).Build(),
new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1980, 1, 1))
.WithHeight(180).Build(),
new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15)).Build(),
new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15))
.WithHeight(180).Build(),
new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15)).Build()
};
public class TransportCentre
{
...
public void PerformTruckDrivingTest(Person person)
{
// Do the test
person.AssignDriverLicense(DriverLicenseType.Truck);
}
}
Building Mocks with NSubstitute
[Test]
public void GivenAPerson_WhenTruckDrivingTestIsCompleted_ThenThePersonIsAssignedALicense()
{
var person = ObjectMother.Persons.John.Build();
var transportCentre = ObjectMother.TransportCentres.BrisbaneCityCentre.Build();
transportCentre.PerformTruckDrivingTest(person);
Assert.That(person.DriverLicenseType, Is.EqualTo(DriverLicenseType.Truck));
}
What’s the actual “Unit” under test?
• PerformTruckDrivingTest()
• Not Person.AssignDriverLicense()
Building Mocks with NSubstitute
[Test]
public void GivenAPerson_WhenTruckDrivingTestIsCompleted_ThenThePersonIsAssignedALicense()
{
var person = ObjectMother.Persons.John.AsProxy().Build();
var transportCentre = ObjectMother.TransportCentres.BrisbaneCityCentre.Build();
transportCentre.PerformTruckDrivingTest(person);
person.Received().AssignDriverLicense(DriverLicenseType.Truck);
}
Building Mocks with NSubstitute
What’s the actual “Unit” under test?
• PerformTruckDrivingTest()
• Not Person.AssignDriverLicense()
Building Mocks with NSubstitute
Caveats:
• Requires a protected parameteress constructor
• Requires the virtual keyword for any properties or methods that need
to be mocked
GitHub: https://github.com/robdmoore/NTestDataBuilder
Twitter: @robdmoore
NTestDataBuilder
Questions

Más contenido relacionado

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Último (20)

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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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 ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

Destacado

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Setup testdata

  • 1. A Better Way to Setup Test Data Poya Manouchehri @PoyaManouchehri poya.manouchehri@readify.net http://askpoya.wordpress.com/
  • 2. 1. Intent is Unclear: • What is 160? • Is nationality important? 2. Test is Brittle: • Changing the constructor will break many tests [Test] public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown() { // Arrange var sarah = new Person("Sarah", "Smith", DateTime.Today.AddYears(-15), 160, "Australian"); // Act / Assert Assert.Throws<InvalidOperationException>(() => sarah.AssignDriverLicense(DriverLicenseType.Automatic)); }
  • 3. public static partial class ObjectMother { public static class Persons { public static Person FifteenYearOldSarah { get { return new Person("Sarah", "Smith", DateTime.Today.AddYears(-17), 160, "Australian"); } } public static Person BrazilianRafael { get { return new Person("Rafael", "Gomez", new DateTime(1985, 12 , 2), 177, “Brazilian") } } } } Object Mother Pattern
  • 4. [Test] public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown() { var sarah = ObjectMother.Persons.FifteenYearOldSarah; Assert.Throws<InvalidOperationException>(() => sarah.AssignDriverLicense(DriverLicenseType.Automatic)); } Object Mother Pattern
  • 5. var person = new PersonBuilder() .WithName("Michael", "Jackson") .BornOn(new DateTime(1958, 8, 29)) .WithHeight(175) .WithNationality("American") .WhoHasDriverLicense(DriverLicenseType.Truck) .Build(); Builder Pattern
  • 6. [Test] public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown() { var person = new PersonBuilder() .BornOn(DateTime.Today.AddYears(-15)) .Build(); Assert.Throws<InvalidOperationException>(() => person.AssignDriverLicense(DriverLicenseType.Automatic)); } Builder Pattern
  • 7. [Test] public void GivenAPersonUnder16_WhenAssigningADriverLicense_ThenAnExceptionIsThrown() { var person = ObjectMother.Persons.Sarah .BornOn(DateTime.Today.AddYears(-15)) .Build(); Assert.Throws<InvalidOperationException>(() => person.AssignDriverLicense(DriverLicenseType.Automatic)); } Builder Pattern
  • 8. var people = PersonBuilder.CreateListOfSize(10) .All().Do(p => p.WithNationality("Australian")) .TheFirst(2).Do(p => p.BornOn(new DateTime(1980, 1, 1))) .TheNext(3).Do(p => p.BornOn(new DateTime(1974, 10, 15))) .Random(2).Do(p => p.WithHeight(180)) .BuildList<Person, PersonBuilder>(); Building Collections with NBuilder var people = new[] { new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1980, 1, 1)).Build(), new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1980, 1, 1)) .WithHeight(180).Build(), new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15)).Build(), new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15)) .WithHeight(180).Build(), new PersonBuilder().WithNationality("Australian").BornOn(new DateTime(1974, 10, 15)).Build() };
  • 9. public class TransportCentre { ... public void PerformTruckDrivingTest(Person person) { // Do the test person.AssignDriverLicense(DriverLicenseType.Truck); } } Building Mocks with NSubstitute
  • 10. [Test] public void GivenAPerson_WhenTruckDrivingTestIsCompleted_ThenThePersonIsAssignedALicense() { var person = ObjectMother.Persons.John.Build(); var transportCentre = ObjectMother.TransportCentres.BrisbaneCityCentre.Build(); transportCentre.PerformTruckDrivingTest(person); Assert.That(person.DriverLicenseType, Is.EqualTo(DriverLicenseType.Truck)); } What’s the actual “Unit” under test? • PerformTruckDrivingTest() • Not Person.AssignDriverLicense() Building Mocks with NSubstitute
  • 11. [Test] public void GivenAPerson_WhenTruckDrivingTestIsCompleted_ThenThePersonIsAssignedALicense() { var person = ObjectMother.Persons.John.AsProxy().Build(); var transportCentre = ObjectMother.TransportCentres.BrisbaneCityCentre.Build(); transportCentre.PerformTruckDrivingTest(person); person.Received().AssignDriverLicense(DriverLicenseType.Truck); } Building Mocks with NSubstitute What’s the actual “Unit” under test? • PerformTruckDrivingTest() • Not Person.AssignDriverLicense()
  • 12. Building Mocks with NSubstitute Caveats: • Requires a protected parameteress constructor • Requires the virtual keyword for any properties or methods that need to be mocked

Notas del editor

  1. A number of techniques for writing tests more clearly and easily. Credit to my colleagues, Rob Moore and Matt Kocaj
  2. Clearer Good for smaller objects with few variations Not suitable when lots of special cases required Can get out of sync