SlideShare a Scribd company logo
1 of 29
Unit Testing
Overview and Best Practices
What’s unit testing?
• Software development process.
• Tests smallest parts of an application.
• Individually and independently.
• Always automated.
Why unit testing?
• Quality
• Test automation
• Bug catching
Why unit testing? cont.
• Documentation
• Design Improving
• Safe Refactoring
• Avoid fear of changes
What’s an unit test?
• Automated piece of code.
• Checks assumptions (state and/or behaviour).
• Unit of work.
• Single end result.
What’s an unit of work?
• Single logical functional use case.
• Public interface.
• A single method, a whole class or multiple classes.
Other levels of testing
• Integration test
• System/E2E test
A good unit test is:
• Fully automated
• Independent
• Isolated
• Deterministic
A good unit test is also:
• Fast
• Unitary
• Readable
• Maintainable
• Trustworthy
Unit Testing Frameworks
• xUnit
• SUnit
xUnit Architecture
• Test Runner
• Test Case
• Test Fixtures
xUnit Architecture cont.
• Test Suites
• Assertions
• Test Result Formatter
A (N)unit test structure
[TestFixture]
public class SimpleTest
{
[Test]
public void ShouldDoSomething()
{
//Given
//When
//Then
}
}
A simple class (SUT)
public class Calculator
{
private double amount;
public Calculator ()
{
amount = 0;
}
public void SetAmount(double value)
{
amount = value;
}
public double GetAmount()
{
return amount;
}
public Calculator Add(double value)
{
amount += value;
return this;
}
}
A simple (N)unit test
[TestFixture]
public class CalculatorTest
{
[Test]
public void ShouldAddAPositiveAmount()
{
//Given
Calculator calculator = new Calculator();
var initialAmount = 10;
var amountToAdd = 30;
var expectedAmount = 40;
calculator.SetAmount(initialAmount);
//When
calculator.Add(amountToAdd);
//Then
Assert.AreEqual(expectedAmount, calculator.GetAmount());
}
}
A class with a dependency
public class Calculator
{
private double amount;
private MathProcessor mathProcessor;
public Calculator (MathProcessor mathProcessor)
{
amount = 0;
self.mathProcessor = mathProcessor;
}
public void SetAmount(double value)
{
amount = value;
}
public double GetAmount()
{
return amount;
}
public Calculator Add(double value)
{
if (value > 1000000) {
amount = mathProcessor.Add(amount, value);
} else {
amount += value;
}
return this;
}
}
A test using mock
[TestFixture]
public class CalculatorTest
{
[Test]
public void ShouldUseMathProcessorForLargeNumbers()
{
//Given
var initialAmount = 10;
var amountToAdd = 3000000;
var expectedAmount = 3000010;
var mathProcessorMock = new Mock<MathProcessor>();
mathProcessorMock.Setup(m=>m.Add()).
Returns(expectedAmount);
Calculator calculator =
new Calculator(mathProcessor.Object);
calculator.SetAmount(initialAmount);
//When
calculator.Add(amountToAdd);
//Then
mathProcessorMock.Verify(m=>m.Add(initialAmount, amountToAdd));
}
}
Test Doubles
• Satisfy SUT dependencies when the actual
implementation can not be used.
Test Doubles
• The most common test doubles are the following:
• Dummies
• Fakes
• Stubs
• Spies
• Mocks
Mocks vs. Stubs
• You DO NOT assert against stubs.
• You MUST assert against mocks.
State verification
• Assert against the object state to make sure its state
is correct.
Behaviour verification
• Assert against mock(s) to check if the expectations
were met.
• Make sure the SUT is calling its dependencies
correctly.
State vs Behaviour
• When to test state?
• When to test behaviour?
State vs Behaviour cont.
• Excessive use of mocking can lead to the following
issues:
• Tests can be harder to understand.
• Tests can be harder to maintain.
• Tests can become less trustworthy.
• Tests can become tautological.
Unit Tests Myths
• It’s a waste of time
• It makes changes more difficult to make
• It slows down the development process
• But it’s such simple code, why write a test?
• Unit testing increases development costs
Making your code testable
• Avoid using singletons and/or static classes and
methods.
• If it’s not possible, try using DI.
• Avoid too many dependencies (more than 3).
Questions?
Thank you!
References
• The Art of Unit Testing, 2nd Edition, Osherove, Roy
• xUnit Test Patterns, Meszaros, Gerard
• http://googletesting.blogspot.com.br/search/label/Tot
T
• http://artofunittesting.com/

More Related Content

What's hot

TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warOleksiy Rezchykov
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PBAbhishek Yadav
 
Unit Testing in WordPress
Unit Testing in WordPressUnit Testing in WordPress
Unit Testing in WordPressBarry Kooij
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentationSanjib Dhar
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 

What's hot (20)

TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Action filter
Action filterAction filter
Action filter
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
testng
testngtestng
testng
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Mini-Training: NFluent
Mini-Training: NFluentMini-Training: NFluent
Mini-Training: NFluent
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
Unit Testing in WordPress
Unit Testing in WordPressUnit Testing in WordPress
Unit Testing in WordPress
 
Mini training - Moving to xUnit.net
Mini training - Moving to xUnit.netMini training - Moving to xUnit.net
Mini training - Moving to xUnit.net
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Test ng
Test ngTest ng
Test ng
 

Similar to Unit testing basics (20)

xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Junit
JunitJunit
Junit
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Unit testing [4] - Software Testing Techniques (CIS640)
Unit testing [4] - Software Testing Techniques (CIS640)Unit testing [4] - Software Testing Techniques (CIS640)
Unit testing [4] - Software Testing Techniques (CIS640)
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Junit
JunitJunit
Junit
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Introducción a TDD
Introducción a TDDIntroducción a TDD
Introducción a TDD
 

More from João Paulo Leonidas Fernandes Dias da Silva (7)

Apache spark intro
Apache spark introApache spark intro
Apache spark intro
 
Kafka basics
Kafka basicsKafka basics
Kafka basics
 
Query driven development
Query driven developmentQuery driven development
Query driven development
 
Recommender Systems
Recommender SystemsRecommender Systems
Recommender Systems
 
OpenCL Heterogeneous Parallel Computing
OpenCL Heterogeneous Parallel ComputingOpenCL Heterogeneous Parallel Computing
OpenCL Heterogeneous Parallel Computing
 
Apache Storm Basics
Apache Storm BasicsApache Storm Basics
Apache Storm Basics
 
Qcon Rio 2015 - Data Lakes Workshop
Qcon Rio 2015 - Data Lakes WorkshopQcon Rio 2015 - Data Lakes Workshop
Qcon Rio 2015 - Data Lakes Workshop
 

Recently uploaded

+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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
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 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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...ICS
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
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
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
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 ApplicationsAlberto González Trastoy
 
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
 
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 CCTVshikhaohhpro
 
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
 

Recently uploaded (20)

+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...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
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 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
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 ...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
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
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
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 ...
 
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
 
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
 

Unit testing basics

  • 1. Unit Testing Overview and Best Practices
  • 2. What’s unit testing? • Software development process. • Tests smallest parts of an application. • Individually and independently. • Always automated.
  • 3. Why unit testing? • Quality • Test automation • Bug catching
  • 4. Why unit testing? cont. • Documentation • Design Improving • Safe Refactoring • Avoid fear of changes
  • 5. What’s an unit test? • Automated piece of code. • Checks assumptions (state and/or behaviour). • Unit of work. • Single end result.
  • 6. What’s an unit of work? • Single logical functional use case. • Public interface. • A single method, a whole class or multiple classes.
  • 7. Other levels of testing • Integration test • System/E2E test
  • 8. A good unit test is: • Fully automated • Independent • Isolated • Deterministic
  • 9. A good unit test is also: • Fast • Unitary • Readable • Maintainable • Trustworthy
  • 10. Unit Testing Frameworks • xUnit • SUnit
  • 11. xUnit Architecture • Test Runner • Test Case • Test Fixtures
  • 12. xUnit Architecture cont. • Test Suites • Assertions • Test Result Formatter
  • 13. A (N)unit test structure [TestFixture] public class SimpleTest { [Test] public void ShouldDoSomething() { //Given //When //Then } }
  • 14. A simple class (SUT) public class Calculator { private double amount; public Calculator () { amount = 0; } public void SetAmount(double value) { amount = value; } public double GetAmount() { return amount; } public Calculator Add(double value) { amount += value; return this; } }
  • 15. A simple (N)unit test [TestFixture] public class CalculatorTest { [Test] public void ShouldAddAPositiveAmount() { //Given Calculator calculator = new Calculator(); var initialAmount = 10; var amountToAdd = 30; var expectedAmount = 40; calculator.SetAmount(initialAmount); //When calculator.Add(amountToAdd); //Then Assert.AreEqual(expectedAmount, calculator.GetAmount()); } }
  • 16. A class with a dependency public class Calculator { private double amount; private MathProcessor mathProcessor; public Calculator (MathProcessor mathProcessor) { amount = 0; self.mathProcessor = mathProcessor; } public void SetAmount(double value) { amount = value; } public double GetAmount() { return amount; } public Calculator Add(double value) { if (value > 1000000) { amount = mathProcessor.Add(amount, value); } else { amount += value; } return this; } }
  • 17. A test using mock [TestFixture] public class CalculatorTest { [Test] public void ShouldUseMathProcessorForLargeNumbers() { //Given var initialAmount = 10; var amountToAdd = 3000000; var expectedAmount = 3000010; var mathProcessorMock = new Mock<MathProcessor>(); mathProcessorMock.Setup(m=>m.Add()). Returns(expectedAmount); Calculator calculator = new Calculator(mathProcessor.Object); calculator.SetAmount(initialAmount); //When calculator.Add(amountToAdd); //Then mathProcessorMock.Verify(m=>m.Add(initialAmount, amountToAdd)); } }
  • 18. Test Doubles • Satisfy SUT dependencies when the actual implementation can not be used.
  • 19. Test Doubles • The most common test doubles are the following: • Dummies • Fakes • Stubs • Spies • Mocks
  • 20. Mocks vs. Stubs • You DO NOT assert against stubs. • You MUST assert against mocks.
  • 21. State verification • Assert against the object state to make sure its state is correct.
  • 22. Behaviour verification • Assert against mock(s) to check if the expectations were met. • Make sure the SUT is calling its dependencies correctly.
  • 23. State vs Behaviour • When to test state? • When to test behaviour?
  • 24. State vs Behaviour cont. • Excessive use of mocking can lead to the following issues: • Tests can be harder to understand. • Tests can be harder to maintain. • Tests can become less trustworthy. • Tests can become tautological.
  • 25. Unit Tests Myths • It’s a waste of time • It makes changes more difficult to make • It slows down the development process • But it’s such simple code, why write a test? • Unit testing increases development costs
  • 26. Making your code testable • Avoid using singletons and/or static classes and methods. • If it’s not possible, try using DI. • Avoid too many dependencies (more than 3).
  • 29. References • The Art of Unit Testing, 2nd Edition, Osherove, Roy • xUnit Test Patterns, Meszaros, Gerard • http://googletesting.blogspot.com.br/search/label/Tot T • http://artofunittesting.com/

Editor's Notes

  1. Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinised for proper operation. Unit testing is always automated.
  2. 1) To focus on quality from the start - it’s impossible for a QA to ad-hoc test the whole system. The best person to test a functionality is the one who developed it. 2) To automate tests - unit tests should always be automated. Automation prevents human errors like forgetting to test a functionality. 3) To catch bugs earlier in the development process - the later in the development process you find a bug, the more expensive it will be to fix it.
  3. 1) To document your code - an example in code is better than lots of lines of text documentation. 2) To improve design (if using TDD) - writing tests first makes your design evolve as needed. You implement a small functionality, makes sure it works and then evolves it. Following this process iteratively often leads to a more simple and elegant design than trying to do everything up front. 3) To allow safe refactoring - refactoring without unit tests is dangerous and error prone. 4) To reduce fear - unit tests encourage us to make changes without the fear of breaking anything.
  4. A unit test is an automated piece of code that invokes the unit of work being tested, and then checks some assumptions about a single end result of that unit.
  5. A unit of work is a single logical functional use case in the system that can be invoked by some public interface. A unit of work can span a single method, a whole class or multiple classes working together to achieve one single logical purpose that can be verified.
  6. 1) Integration tests are tests that verify the interface between system components or modules, like external services, databases and file systems. 2) End to end tests are tests that traverse all the system layers (e.g. from the UI down to the database). Both types of tests can be automated.
  7. Needs to be able to be fully automated. There’s should be no need for any external intervention in order to run the test. 2) It can be run in any order if part of many other tests. There should be no dependencies between tests. 3) It has full control over all the pieces running. Doubles may be used to achieve this isolation when needed. A unit test runs in memory. There’s no DB or File access, for example. 4) Consistently returns the same result (deterministic). You always run the same test, so no random numbers, for example. Save those for integration tests.
  8. 1) Runs fast. 2) Tests a single logical concept in the system. 3) Readable. 4) Maintainable. 5) Trustworthy. When you see its result, you don’t need to debug the code just to be sure.
  9. xUnit - is the collective name for several unit testing frameworks that derive their structure and functionality from Smalltalk's SUnit. SUnit, designed by Kent Beck in 1998. It was written in a highly-structured object-oriented style, which lent easily to contemporary languages such as Java (JUnit) and C# (NUnit).
  10. Test Runner - Is an executable program that runs tests implemented using an xUnit framework and reports the test results. Test Case - Is the most elemental class. All unit tests are inherited from here. Test Fixtures - A test fixture (also known as a test context) is the set of preconditions or state needed to run a test. The developer should set up a known good state before the tests, and return to the original state after the tests.
  11. Test Suites - A test suite is a set of tests that all share the same fixture. The order of the tests shouldn't matter. Assertions - An assertion is a function or macro that verifies the state (or behaviour) of the unit under test. Usually an assertion expresses a logical condition that is true for results expected in a correctly running system under test (SUT). Failure of an assertion typically throws an exception, aborting the execution of the current test. Test Result Formatter - A test runner produces results in one or more output formats. In addition to a plain, human-readable format, there is often a test result formatter that produces XML output.
  12. Whenever the SUT has a dependency and it’s not possible (or desirable) to use the actual implementation, we use test doubles to satisfy this dependency so our tests can run properly.
  13. 1) Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. 2) Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example). 3) Stubs are objects that provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. We use stubs when we want to isolate our SUT from its dependencies. 4) Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent. 5) Mocks are objects that are pre-programmed with expectations which form a specification of the calls they are expected to receive. We use mocks when we want to test the behaviour of our SUT. We do that by verifying if the expected methods of the mock were called or not.
  14. A mock framework (Moq, RhinoMocks, etc.) can create both mocks and stubs. The differences between mocks and stubs are the following: You DO NOT assert against stubs. They are used only to replace the actual dependency implementation in order to isolate the SUT from its dependencies. You DO/MUST assert against mocks. Most mocks frameworks provide a method called verify which is used to check whether the expectations that were set on the mock object were met, i.e, the methods were actually called. We can say that mocks are stubs that are used in assertions. A mock can make a test fail, a stub can’t.
  15. It’s when, after you call the method under test, you assert against the object state to check if this method left the object in the expected state. In this case we want to make sure the method under test sets the object state correctly.
  16. It’s when, after you call the method under test, you assert against the mock(s) to check if the expectations were met, i.e, the expected methods on the mock(s) were called. In this case we want to make sure the method under test is calling its dependencies methods correctly. (Right order, right parameters, etc.)
  17. When to test state? Whenever it’s possible, i.e, when the method under test changes the state of the object being tested or returns a result (not void). When to test behaviour? 1) When the method under test has no side effect on the object being tested and/or does not return a result. Example: a Save method which does not change the state of the object being saved but calls a Logger class to log success or failure of the Save method. 2) When testing the return result and/or state of the object under test is not enough to guarantee correctness. Example: A Save method that returns the saved object also needs to decide if it should log to the file system or send an email, depending on a given business rule, although its result will always be the same (The saved object). 3) When the number and order of the calls to dependencies methods matter. If you need to guarantee that a call to the Save method will send only one email or log only one entry to the file system.
  18. Sometimes, testing only the behaviour does not guarantee that the returned result will be correct. You may end up just checking if the dependencies are being called correctly and not if they are doing the right thing. Excessive use of mocking can lead to the following issues: 1) Tests can be harder to understand - all that mock set up can distract you from the actual purpose of the test. 2) Tests can be harder to maintain - When you set up a mock you’re leaking implementation details into your test. If you change the implementation you also need to change your tests. Tests should know little or nothing about the implementation and focus only in the public interface of the SUT. 3) Tests can become less trustworthy - When you tell a mock how to behave, the only assurance you get with your tests is that your code will work if your mocks behave exactly like your real implementations. This can be very hard to guarantee, and the problem gets worse as your code changes over time, as the behaviour of the real implementations is likely to get out of sync with your mocks. 4) Tests can become tautological, i.e, redundant. A tautological tests it’s just a copy of the implementation.
  19. 1) What’s a waste of time? · Fixing the same bugs over and over · Writing and rewriting proofs throughout the development process · Fixing one bug, only to have another one magically appearing somewhere else · Getting interrupted in the middle of coding and completely losing your way. Resistance to unit testing is understandable, but many developers come around to understand its benefits once they complete a project with unit testing. 2) Not only is this false, it’s in fact the opposite. One of the biggest benefits of doing unit testing is the ability to implement large changes and immediately check that your changes have been done properly. Making changes and then later realizing that it’s affected other parts of your software, and then trying to isolate what caused the issue, is what not only makes changes difficult to make, it also causes developers to be wary of making changes. 3) Running unit tests might initially make the process seem slower, but the reality is that it saves time by preventing mistakes and recognizing them before the process goes too far. It also allows developers to have more confidence in the work they’ve already completed, thus clearing the way for progress. And throughout the life of the development process, the advantages of using unit testing can result in spending less time. 4) It seems simple, until something goes wrong. And then things aren’t so simple any more. Writing a unit test, even for simple code, adds stability and security to a project. 5) By decreasing the difficulty of implementing large changes, developers can be more flexible to the needs of the product itself, thus increasing chances for financial success.
  20. Static classes and methods are harder to mock/stub. 2) Dependency injection. Inject the object returned by the singleton or static method into your SUT. 3) If your SUT has too many dependencies your test may become harder to implement and understand.