SlideShare a Scribd company logo
Unit Test
THE WAY OF THE FORCE
Francesco Garavaglia
01/2016
 Why Unit Test
 Terminology / definition
 TDD
 Test in practice
AGENDA
2
3
Why
Why 3
Why should we TEST?
 Why should we test at all?
REMEMBER
Testing is
just one
step in QA
4
“I don’t have time
to write tests
because I am too
busy debugging.”
5
Why have unit tests?
 Why have unit tests?
 Find bugs early / fast feedback
 Increase QA
 Why not to have unit tests
 Increases development time?
CostOfWritingUnitTests < Sum(BugFixing)
6
Unit Test You will
Do, Powerful you
will be
8
Terminology /
definition
88
The Concept of Unit Testing
 A unit test is code written by a developer that tests as small a piece of functionality (the unit) as
possible.
 One function may have multiple unit tests according to the usage and outputs of the function.
 Tests ensure
 The code meets expectations and specifications: Does what it says it should do.
 The code continues to meet expectations over time: Avoiding regression.
9
10
Unit testing is a method by which individual units of source
code are tested to determine if they are fit for use.
One can view a unit as the smallest testable part of an
application.
Unit tests are created by programmers or occasionally by
white box testers during the development process.
Unit?
A Silver Bullet
Unit Test is not
12
Test Driven
Design
1212
 Test Driven Design
 It’s NOT testing, but using tests to DRIVE the
design
 As a side-effect, you got unit tests!
With good level of coverage!
13TDD: Test Driven Design
14
RED
GREEN
REFACTOR
Write a failing test. With empty class/method.
Fill in the class/method implementation. Make the tests pass.
Make code better.
Unit Testing Tools
Production
Code
Unit Test
Code
Test
Runner
15
Types of Software Testing
UnitTesting (do the
parts perform
correctly alone?)
IntegrationTesting
(do the parts
perform correctly
together?)
User Acceptance
Testing (does the
system meet the end
user’s expectations?)
16
Unit Testing vs. Integration Testing
Busines
s Entity
Data
Layer
Data
Access
Layer
User
Interfa
ce
Unit Testing tests one layer
Integration Testing tests across layers.
17
Unit Test Hierarchy
Test Project
Test
Fixture
Test Test Test Test
Test
Fixture
Test Test Test Test
One per assembly
One per class
One per unit (not
necessarily per
method)
18
19
Terminology /
definition
1919
What does a unit test look like?
Using NUnit.Framework;
[TestFixture]
public class CarTests
{
[Test]
public voidTest_Car_Paint ()
{
// Arrange
Color paint = Color.Red;
Car car = new Car();
// Act
car.paint(Color.Red);
// Assert
Assert.AreEqual(car.Color, paint);
}
…
}
20
Structure of A Unit Test
 Setup
 Prepare an input
 Call a method
 Check an output
 Tear down
21
Test Assertions
 Assertions are the ‘checks’ that you may perform to determine if a test passes or fails.
 For instance:
 Assert.IsTrue()
 Assert.IsInstance()
 Assert.AreEqual()
 Generally speaking, you want ONE assertion per test.
22
Unit Testing with Mocks
Busines
s Entity
Data
Layer
Data
Access
Layer
Unit Testing tests one layer
A Mock allows a
dependency to be imitated
so the Unit test can be
isolated.
23
Executing Tests
Manually:
1. Compile Test project (to .dll or .exe)
2. Open in Test runner.
3. Select and execute tests.
Automatically:
1. Build server compiles and runs tests as part of nightly build operation.
2. Any test failures = entire build fails.
24
The right way
you know now
26
Best Practices
26
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or loops
6. No exception handling
7. Informative Assertion messages
8. No test logic in production code
9. Separation per business module
10. Separation per type
27
Consistent
 Multiple runs of the test should consistently return true or consistently return false, provided no
changes were made on code
Code that can cause problems:
Dim currentDate as Date = Now()
Dim value as Integer = New Random().Next
28
Atomic
 Only two possible results: PASS or FAIL
 No partially successful tests.
 Isolation of tests:
 Different execution order must yield same results.
 Test B should not depend on outcome of Test A
 Use Mocks instead.
29
Single Responsibility
 One test should be responsible for one scenario only.
 Test behavior, not methods:
 One method, multiple behaviors  Multiple tests
 One behavior, multiple methods  One test
30
Single Responsibility
Sub TestMethod()
Assert.IsTrue(behavior1)
Assert.IsTrue(behavior2)
Assert.IsTrue(behavior3)
End Sub
Sub TestMethodCheckBehavior1()
Assert.IsTrue(behavior1)
End Sub
Sub TestMethodCheckBehavior2()
Assert.IsTrue(behavior2)
End Sub
Sub TestMethodCheckBehavior3()
Assert.IsTrue(behavior3)
End Sub
31
Self Descriptive
 Unit test must be easy to read and understand
 Variable Names
 Method Names
 Class Names
 No conditional logic
 No loops
 Name tests to represent PASS conditions:
 Public Sub CanMakeReservation()
 Public Sub TotalBillEqualsSumOfMenuItemPrices()
Self descriptive
32
No conditional logic or loops
 Test should have no uncertainty:
 All inputs should be known
 Method behavior should be predictable
 Expected output should be strictly defined
 Split in to two tests rather than using “If” or “Case”
 Tests should not contain “While”, “Do While” or “For” loops.
 If test logic has to be repeated, it probably means the test is too complicated.
 Call method multiple times rather than looping inside of method.
33
No conditional logic or loops
Sub TestBeforeOrAfter()
If before Then
Assert.IsTrue(behavior1)
ElseIf after Then
Assert.IsTrue(behavior2)
Else
Assert.IsTrue(behavior3)
End If
End Sub
Sub TestBefore()
Dim before as Boolean = true
Assert.IsTrue(behavior1)
End Sub
Sub TestAfter()
Dim after as Boolean = true
Assert.IsTrue(behavior2)
End Sub
Sub TestNow()
Dim before as Boolean = false
Dim after as Boolean = false
Assert.IsTrue(behavior3)
End Sub
34
No Exception Handling
 Indicate expected exception with attribute.
 Catch only the expected type of exception.
 Fail test if expected exception is not caught.
 Let other exceptions go uncaught.
35
No Exception Handling
<ExpectedException(“MyException”)> _
Sub TestException()
myMethod(parameter)
Assert.Fail(“MyException expected.”)
End Sub
36
Informative Assertion Messages
 By reading the assertion message, one should know why the test failed and what to do.
 Include business logic information in the assertion message (such as input values, etc.)
 Good assertion messages:
 Improve documentation of the code,
 Inform developers about the problem if the test fails.
37
No test logic in Production Code
 Separate Unit tests and Production code in separate projects.
 Do not create Methods or Properties used only by unit tests.
 Use Dependency Injection or Mocks to isolate Production code.
38
Separation per Business Module
 Create separate test project for every layer or assembly
 Decrease execution time of test suites by splitting in to smaller suites
 Suite 1 - All Factories
 Suite II - All Controllers
 Smaller Suites can be executed more frequently
39
Separation per Type
 Align Test Fixtures with type definitions.
 Reminder: Unit tests are separate from integration tests!
 Different purpose
 Different frequency
 Different time of execution
 Different action in case of failure
40
Use the tests
Thanks
FRANCESCO.GARAVAGLIA@GMAIL.COM

More Related Content

What's hot (20)

PDF
Test Driven Development (TDD)
David Ehringer
 
PPSX
Junit
FAROOK Samath
 
PPTX
Unit test
Tran Duc
 
PPTX
Unit Testing
Sergey Podolsky
 
PDF
Code Coverage
Ernani Omar Cruz
 
PPS
Unit Testing
Anuj Arora
 
PPTX
Unit Tests And Automated Testing
Lee Englestone
 
PDF
Test cases
Chandra Maddigapu
 
PPS
JUnit Presentation
priya_trivedi
 
PDF
Unit Testing in Angular
Knoldus Inc.
 
PPT
Google test training
Thierry Gayet
 
PPTX
Angular Unit Testing
Shailendra Chauhan
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PDF
Clean Unit Test Patterns
Frank Appel
 
PDF
Mockito a simple, intuitive mocking framework
Phat VU
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PDF
Mocking in Java with Mockito
Richard Paul
 
PPTX
Mutation Testing: Testing your tests
Stephen Leigh
 
PPTX
Automation testing & Unit testing
Kapil Rajpurohit
 
PPTX
UNIT TESTING PPT
suhasreddy1
 
Test Driven Development (TDD)
David Ehringer
 
Unit test
Tran Duc
 
Unit Testing
Sergey Podolsky
 
Code Coverage
Ernani Omar Cruz
 
Unit Testing
Anuj Arora
 
Unit Tests And Automated Testing
Lee Englestone
 
Test cases
Chandra Maddigapu
 
JUnit Presentation
priya_trivedi
 
Unit Testing in Angular
Knoldus Inc.
 
Google test training
Thierry Gayet
 
Angular Unit Testing
Shailendra Chauhan
 
Angular Unit Testing
Alessandro Giorgetti
 
Clean Unit Test Patterns
Frank Appel
 
Mockito a simple, intuitive mocking framework
Phat VU
 
JUnit & Mockito, first steps
Renato Primavera
 
Mocking in Java with Mockito
Richard Paul
 
Mutation Testing: Testing your tests
Stephen Leigh
 
Automation testing & Unit testing
Kapil Rajpurohit
 
UNIT TESTING PPT
suhasreddy1
 

Viewers also liked (20)

PPTX
Tdd & unit test
GomathiNayagam S
 
PDF
PostgreSQL Day italy 2016 Unit Test
Andrea Adami
 
PDF
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Howard Deiner
 
PPTX
Unbox yourself Into Testing
vodqancr
 
PDF
Inverting The Testing Pyramid
Naresh Jain
 
PPTX
Testing web application
jayashreesaravanan
 
PDF
Agile Testing Framework - The Art of Automated Testing
Dimitri Ponomareff
 
PDF
Unit Test + Functional Programming = Love
Alvaro Videla
 
PDF
Web application testing with Selenium
Kerry Buckley
 
PPTX
Magic book 2 unit 1 pres
Dora Kouri
 
PPTX
Osterman media summary
Patrick Osterman
 
PPT
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
socdomgppu
 
PPT
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
H. Beecher Hicks III
 
PPTX
Network management overview
Sarah Meyer
 
PPTX
Business Insights ICT
Dimitris Alexandratos
 
PPT
780335 slides (1)
Sue Rosen RN CLNC
 
PPT
ReadingFirstv3
Mark Anthony Hauck
 
PPTX
Sports+exercices full
Dora Kouri
 
PPTX
Arthritis foods to avoid
brooke123
 
PPTX
General Service Contractors Presentation
Julia Albaugh
 
Tdd & unit test
GomathiNayagam S
 
PostgreSQL Day italy 2016 Unit Test
Andrea Adami
 
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Howard Deiner
 
Unbox yourself Into Testing
vodqancr
 
Inverting The Testing Pyramid
Naresh Jain
 
Testing web application
jayashreesaravanan
 
Agile Testing Framework - The Art of Automated Testing
Dimitri Ponomareff
 
Unit Test + Functional Programming = Love
Alvaro Videla
 
Web application testing with Selenium
Kerry Buckley
 
Magic book 2 unit 1 pres
Dora Kouri
 
Osterman media summary
Patrick Osterman
 
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
socdomgppu
 
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
H. Beecher Hicks III
 
Network management overview
Sarah Meyer
 
Business Insights ICT
Dimitris Alexandratos
 
780335 slides (1)
Sue Rosen RN CLNC
 
ReadingFirstv3
Mark Anthony Hauck
 
Sports+exercices full
Dora Kouri
 
Arthritis foods to avoid
brooke123
 
General Service Contractors Presentation
Julia Albaugh
 
Ad

Similar to Workshop unit test (20)

PPTX
TDD Best Practices
Attila Bertók
 
PPTX
Unit testing
Panos Pnevmatikatos
 
PPT
Unit testing
Murugesan Nataraj
 
PPTX
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove
 
PPTX
Unit testing
PiXeL16
 
PPTX
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
PDF
An introduction to unit testing
Adam Stephensen
 
PDF
What is Unit Testing_ - A Complete Guide.pdf
kalichargn70th171
 
PDF
What is Unit Testing? - A Complete Guide
flufftailshop
 
PDF
Writing Tests Effectively
Paul Boocock
 
PPT
types of testing with descriptions and examples
Mani Deepak Choudhry
 
PDF
Are Your Continuous Tests Too Fragile for Agile?
Parasoft
 
PDF
What Is Unit Testing A Complete Guide With Examples.pdf
Jace Reed
 
PPTX
1.1 Chapter_22_ Unit Testing-testing (1).pptx
tiyaAbid
 
PDF
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
PDF
What Is Unit Testing_ A Complete Guide With Examples.pdf
Steve Wortham
 
PDF
How Unit Testing Strengthens Software Reliability
Shubham Joshi
 
PPTX
Unit testing
princezzlove
 
PDF
Unit testing - An introduction
Alejandro Claro Mosqueda
 
PPTX
Making the Unstable Stable - An Intro To Testing
Cameron Presley
 
TDD Best Practices
Attila Bertók
 
Unit testing
Panos Pnevmatikatos
 
Unit testing
Murugesan Nataraj
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove
 
Unit testing
PiXeL16
 
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
An introduction to unit testing
Adam Stephensen
 
What is Unit Testing_ - A Complete Guide.pdf
kalichargn70th171
 
What is Unit Testing? - A Complete Guide
flufftailshop
 
Writing Tests Effectively
Paul Boocock
 
types of testing with descriptions and examples
Mani Deepak Choudhry
 
Are Your Continuous Tests Too Fragile for Agile?
Parasoft
 
What Is Unit Testing A Complete Guide With Examples.pdf
Jace Reed
 
1.1 Chapter_22_ Unit Testing-testing (1).pptx
tiyaAbid
 
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
What Is Unit Testing_ A Complete Guide With Examples.pdf
Steve Wortham
 
How Unit Testing Strengthens Software Reliability
Shubham Joshi
 
Unit testing
princezzlove
 
Unit testing - An introduction
Alejandro Claro Mosqueda
 
Making the Unstable Stable - An Intro To Testing
Cameron Presley
 
Ad

More from Francesco Garavaglia (7)

PPTX
Introduction to DevOps
Francesco Garavaglia
 
PPTX
Entering the matrix
Francesco Garavaglia
 
PPTX
Workshop - cqrs brief introduction
Francesco Garavaglia
 
PDF
CQRS recepies
Francesco Garavaglia
 
PDF
IOC in Unity
Francesco Garavaglia
 
PDF
IOC in unity
Francesco Garavaglia
 
PDF
Work shop eventstorming
Francesco Garavaglia
 
Introduction to DevOps
Francesco Garavaglia
 
Entering the matrix
Francesco Garavaglia
 
Workshop - cqrs brief introduction
Francesco Garavaglia
 
CQRS recepies
Francesco Garavaglia
 
IOC in Unity
Francesco Garavaglia
 
IOC in unity
Francesco Garavaglia
 
Work shop eventstorming
Francesco Garavaglia
 

Recently uploaded (20)

PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 

Workshop unit test

  • 1. Unit Test THE WAY OF THE FORCE Francesco Garavaglia 01/2016
  • 2.  Why Unit Test  Terminology / definition  TDD  Test in practice AGENDA 2
  • 4. Why should we TEST?  Why should we test at all? REMEMBER Testing is just one step in QA 4
  • 5. “I don’t have time to write tests because I am too busy debugging.” 5
  • 6. Why have unit tests?  Why have unit tests?  Find bugs early / fast feedback  Increase QA  Why not to have unit tests  Increases development time? CostOfWritingUnitTests < Sum(BugFixing) 6
  • 7. Unit Test You will Do, Powerful you will be
  • 9. The Concept of Unit Testing  A unit test is code written by a developer that tests as small a piece of functionality (the unit) as possible.  One function may have multiple unit tests according to the usage and outputs of the function.  Tests ensure  The code meets expectations and specifications: Does what it says it should do.  The code continues to meet expectations over time: Avoiding regression. 9
  • 10. 10 Unit testing is a method by which individual units of source code are tested to determine if they are fit for use. One can view a unit as the smallest testable part of an application. Unit tests are created by programmers or occasionally by white box testers during the development process. Unit?
  • 11. A Silver Bullet Unit Test is not
  • 13.  Test Driven Design  It’s NOT testing, but using tests to DRIVE the design  As a side-effect, you got unit tests! With good level of coverage! 13TDD: Test Driven Design
  • 14. 14 RED GREEN REFACTOR Write a failing test. With empty class/method. Fill in the class/method implementation. Make the tests pass. Make code better.
  • 15. Unit Testing Tools Production Code Unit Test Code Test Runner 15
  • 16. Types of Software Testing UnitTesting (do the parts perform correctly alone?) IntegrationTesting (do the parts perform correctly together?) User Acceptance Testing (does the system meet the end user’s expectations?) 16
  • 17. Unit Testing vs. Integration Testing Busines s Entity Data Layer Data Access Layer User Interfa ce Unit Testing tests one layer Integration Testing tests across layers. 17
  • 18. Unit Test Hierarchy Test Project Test Fixture Test Test Test Test Test Fixture Test Test Test Test One per assembly One per class One per unit (not necessarily per method) 18
  • 20. What does a unit test look like? Using NUnit.Framework; [TestFixture] public class CarTests { [Test] public voidTest_Car_Paint () { // Arrange Color paint = Color.Red; Car car = new Car(); // Act car.paint(Color.Red); // Assert Assert.AreEqual(car.Color, paint); } … } 20
  • 21. Structure of A Unit Test  Setup  Prepare an input  Call a method  Check an output  Tear down 21
  • 22. Test Assertions  Assertions are the ‘checks’ that you may perform to determine if a test passes or fails.  For instance:  Assert.IsTrue()  Assert.IsInstance()  Assert.AreEqual()  Generally speaking, you want ONE assertion per test. 22
  • 23. Unit Testing with Mocks Busines s Entity Data Layer Data Access Layer Unit Testing tests one layer A Mock allows a dependency to be imitated so the Unit test can be isolated. 23
  • 24. Executing Tests Manually: 1. Compile Test project (to .dll or .exe) 2. Open in Test runner. 3. Select and execute tests. Automatically: 1. Build server compiles and runs tests as part of nightly build operation. 2. Any test failures = entire build fails. 24
  • 25. The right way you know now
  • 27. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type 27
  • 28. Consistent  Multiple runs of the test should consistently return true or consistently return false, provided no changes were made on code Code that can cause problems: Dim currentDate as Date = Now() Dim value as Integer = New Random().Next 28
  • 29. Atomic  Only two possible results: PASS or FAIL  No partially successful tests.  Isolation of tests:  Different execution order must yield same results.  Test B should not depend on outcome of Test A  Use Mocks instead. 29
  • 30. Single Responsibility  One test should be responsible for one scenario only.  Test behavior, not methods:  One method, multiple behaviors  Multiple tests  One behavior, multiple methods  One test 30
  • 31. Single Responsibility Sub TestMethod() Assert.IsTrue(behavior1) Assert.IsTrue(behavior2) Assert.IsTrue(behavior3) End Sub Sub TestMethodCheckBehavior1() Assert.IsTrue(behavior1) End Sub Sub TestMethodCheckBehavior2() Assert.IsTrue(behavior2) End Sub Sub TestMethodCheckBehavior3() Assert.IsTrue(behavior3) End Sub 31
  • 32. Self Descriptive  Unit test must be easy to read and understand  Variable Names  Method Names  Class Names  No conditional logic  No loops  Name tests to represent PASS conditions:  Public Sub CanMakeReservation()  Public Sub TotalBillEqualsSumOfMenuItemPrices() Self descriptive 32
  • 33. No conditional logic or loops  Test should have no uncertainty:  All inputs should be known  Method behavior should be predictable  Expected output should be strictly defined  Split in to two tests rather than using “If” or “Case”  Tests should not contain “While”, “Do While” or “For” loops.  If test logic has to be repeated, it probably means the test is too complicated.  Call method multiple times rather than looping inside of method. 33
  • 34. No conditional logic or loops Sub TestBeforeOrAfter() If before Then Assert.IsTrue(behavior1) ElseIf after Then Assert.IsTrue(behavior2) Else Assert.IsTrue(behavior3) End If End Sub Sub TestBefore() Dim before as Boolean = true Assert.IsTrue(behavior1) End Sub Sub TestAfter() Dim after as Boolean = true Assert.IsTrue(behavior2) End Sub Sub TestNow() Dim before as Boolean = false Dim after as Boolean = false Assert.IsTrue(behavior3) End Sub 34
  • 35. No Exception Handling  Indicate expected exception with attribute.  Catch only the expected type of exception.  Fail test if expected exception is not caught.  Let other exceptions go uncaught. 35
  • 36. No Exception Handling <ExpectedException(“MyException”)> _ Sub TestException() myMethod(parameter) Assert.Fail(“MyException expected.”) End Sub 36
  • 37. Informative Assertion Messages  By reading the assertion message, one should know why the test failed and what to do.  Include business logic information in the assertion message (such as input values, etc.)  Good assertion messages:  Improve documentation of the code,  Inform developers about the problem if the test fails. 37
  • 38. No test logic in Production Code  Separate Unit tests and Production code in separate projects.  Do not create Methods or Properties used only by unit tests.  Use Dependency Injection or Mocks to isolate Production code. 38
  • 39. Separation per Business Module  Create separate test project for every layer or assembly  Decrease execution time of test suites by splitting in to smaller suites  Suite 1 - All Factories  Suite II - All Controllers  Smaller Suites can be executed more frequently 39
  • 40. Separation per Type  Align Test Fixtures with type definitions.  Reminder: Unit tests are separate from integration tests!  Different purpose  Different frequency  Different time of execution  Different action in case of failure 40