SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Moq presentation
Moq presentationMoq presentation
Moq presentation
LynxStar
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 

Was ist angesagt? (20)

JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Unit testing
Unit testingUnit testing
Unit testing
 
05 junit
05 junit05 junit
05 junit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Moq presentation
Moq presentationMoq presentation
Moq presentation
 
Google test training
Google test trainingGoogle test training
Google test training
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
 
Unit test
Unit testUnit test
Unit test
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Test Automation Pyramid
Test Automation PyramidTest Automation Pyramid
Test Automation Pyramid
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 

Andere mochten auch

Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About ItWhy Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Howard Deiner
 
Inverting The Testing Pyramid
Inverting The Testing PyramidInverting The Testing Pyramid
Inverting The Testing Pyramid
Naresh Jain
 
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
socdomgppu
 
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
H. Beecher Hicks III
 
Arthritis foods to avoid
Arthritis foods to avoidArthritis foods to avoid
Arthritis foods to avoid
brooke123
 
General Service Contractors Presentation
General Service Contractors Presentation General Service Contractors Presentation
General Service Contractors Presentation
Julia Albaugh
 

Andere mochten auch (20)

Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
PostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit TestPostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit Test
 
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About ItWhy Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
Why Johnny Can't Unit Test His Legacy Code - And What You Can Do About It
 
Unbox yourself Into Testing
Unbox yourself Into TestingUnbox yourself Into Testing
Unbox yourself Into Testing
 
Inverting The Testing Pyramid
Inverting The Testing PyramidInverting The Testing Pyramid
Inverting The Testing Pyramid
 
Testing web application
Testing web applicationTesting web application
Testing web application
 
Agile Testing Framework - The Art of Automated Testing
Agile Testing Framework - The Art of Automated TestingAgile Testing Framework - The Art of Automated Testing
Agile Testing Framework - The Art of Automated Testing
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
Web application testing with Selenium
Web application testing with SeleniumWeb application testing with Selenium
Web application testing with Selenium
 
Magic book 2 unit 1 pres
Magic book 2 unit 1 presMagic book 2 unit 1 pres
Magic book 2 unit 1 pres
 
Osterman media summary
Osterman media summaryOsterman media summary
Osterman media summary
 
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
Художественная интернет выставка художников из Украины, города Черкассы (2 ча...
 
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
Red Clay Capital - The Competitive Reality of Supplier Diversity: A Procureme...
 
Network management overview
Network management overviewNetwork management overview
Network management overview
 
Business Insights ICT
Business Insights ICTBusiness Insights ICT
Business Insights ICT
 
780335 slides (1)
780335 slides (1)780335 slides (1)
780335 slides (1)
 
ReadingFirstv3
ReadingFirstv3ReadingFirstv3
ReadingFirstv3
 
Sports+exercices full
Sports+exercices fullSports+exercices full
Sports+exercices full
 
Arthritis foods to avoid
Arthritis foods to avoidArthritis foods to avoid
Arthritis foods to avoid
 
General Service Contractors Presentation
General Service Contractors Presentation General Service Contractors Presentation
General Service Contractors Presentation
 

Ähnlich wie Workshop unit test

Software testing
Software testingSoftware testing
Software testing
Bala Ganesh
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 
Unit testing
Unit testingUnit testing
Unit testing
medsherb
 
Software Testing Tecniques
Software Testing TecniquesSoftware Testing Tecniques
Software Testing Tecniques
ersanbilik
 

Ähnlich wie Workshop unit test (20)

SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Unit testing
Unit testingUnit testing
Unit testing
 
Software testing
Software testingSoftware testing
Software testing
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing
TestingTesting
Testing
 
Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
Testing
TestingTesting
Testing
 
Software Testing Tecniques
Software Testing TecniquesSoftware Testing Tecniques
Software Testing Tecniques
 

Mehr von Francesco Garavaglia (7)

Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
Entering the matrix
Entering the matrixEntering the matrix
Entering the matrix
 
Workshop - cqrs brief introduction
Workshop - cqrs brief introductionWorkshop - cqrs brief introduction
Workshop - cqrs brief introduction
 
CQRS recepies
CQRS recepiesCQRS recepies
CQRS recepies
 
IOC in Unity
IOC in Unity  IOC in Unity
IOC in Unity
 
IOC in unity
IOC in unityIOC in unity
IOC in unity
 
Work shop eventstorming
Work shop  eventstormingWork shop  eventstorming
Work shop eventstorming
 

Kürzlich hochgeladen

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Kürzlich hochgeladen (20)

%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 

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