SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Building Unit Tests correctly with VS 2013
About.ME
• Senior Consultant @CodeValue
• Developing software (Professionally) since 2002
• Mocking code since 2008
• Test driven professional
• Blogger: http://blog.drorhelper.com
/*
* You may think you know what the following code does.
* But you dont. Trust me.
* Fiddle with it, and youll spend many a sleepless
* night cursing the moment you thought youd be clever
* enough to "optimize" the code below.
* Now close this file and go play with something else.
*/
//
// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42
//
//This code sucks, you know it and I know it.
//Move on and call me an idiot later.
http://stackoverflow.com/questions/184618/what-is-the-
best-comment-in-source-code-you-have-ever-encountered
We fear our code!
//Abandon all hope ye who enter beyond this point
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
// I dedicate all this code, all my work, to my wife, Darlene, who will
// have to support me and our three children and the dog once it gets
// released into the public.
//The following 1056 lines of code in this next method
//is a line by line port from VB.NET to C#.
//I ported this code but did not write the original code.
//It remains to me a mystery as to what
//the business logic is trying to accomplish here other than to serve as
//some sort of a compensation shell game invented by a den of thieves.
//Oh well, everyone wants this stuff to work the same as before.
//I guess the devil you know is better than the devil you don't.
“If we’re afraid to change
the very thing we’ve
created,
we failed as professionals”
Robert C. Martin
Legacy code
“Code without tests is bad code...
With tests, we can change the
behavior of our code quickly and
verifiably...”
Michael Feathers - “Working effectively with legacy code”
This is a unit test
[Test]
public void CheckPassword_ValidUser_ReturnTrue()
{
bool result = CheckPassword(“user”, “pass”);
Assert.That(result, Is.True);
}
D
This is also a unit test
[TestMethod]
public void CheckPassword_ValidUser_ReturnTrue()
{
bool result = CheckPassword(“user”, “pass”);
Assert.IsTrue(result);
}
D
A unit test is…
1. Tests specific functionality
2. Clear pass/fail criteria
3. Good unit test runs in isolation
Unit testing is an iterative effort
Unit testing is an iterative effort
There’s more to unit tests then just “tests”
Written by the developer who wrote the code
Quick feedback
Avoid stupid bugs
Immune to regression
Change your code without fear
In code documentation
13
copyright 2008 trainologic LTD
13
One last reason
You’re already Testing your code – manually
So why not save the time?
The cost of unit testing
120%
135%
115%
125%
0%
20%
40%
60%
80%
100%
120%
140%
IBM: Drivers MS: Windows MS: MSN MS: VS
Time taken to code a feature
WithoutTDD Using TDD
The value of unit testing
61%
38%
24%
9%
0%
20%
40%
60%
80%
100%
120%
140%
IBM: Drivers MS: Windows MS: MSN MS: VS
Using Test Driven Design
Time To Code Feature Defect density of team
Major quality improvement for minor time investment
The cost of bugs
0
1
2
3
4
5
6
7
8
9
10
0%
20%
40%
60%
80%
100%
Thousand$s
%defectscreated
Where does it hurt?
% of Defects Introduced Cost to Fix a Defect
The pain is here! This is too late…
Supporting environment
• The team
• Development environment
The Team
• The team commitment is important
• Learn from test reviews
• Track results
Tools of the trade
Server Dev Machine
Source
Control
Build Server
Test Runner
Code
CoverageBuild Script
Unit Testing
Framework
Isolation
Framework
Development environment
• Make it easy to write and run tests
– Unit test framework
– Test Runner
– Isolation framework
• Know where you stand
– Code coverage
Unit testing frameworks
• Create test fixtures
• Assert results
• Additional utilities
• Usually provide command-line/GUI runner
http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks
[Test]
public void AddTest()
{
var cut = new Calculator();
var result = cut.Add(2, 3);
Assert.AreEqual(5, result);
}
This is not a real unit test
Real code has dependencies
Unit test
Code under test
Dependency Dependency
The solution - Mocking
Fake object(s)
Unit test
Code under test
Dependency
Isolation
• Replace production logic with custom logic
• We do this in order to
– Focus the test on one class only
– Test Interaction
– Simplify Unit test writing
What Mocking framework can do for you?
• Create Fake objects
• Set behavior on fake objects
• Verify method was called
• And more...
[Test]
public void IsLoginOK_LoggerThrowsException_CallsWebService()
{
var fakeLogger = Isolate.Fake.Instance<ILogger>();
Isolate
.WhenCalled(() => fakeLogger.Write(""))
.WillThrow(new LoggerException());
var fakeWebService = Isolate.Fake.Instance<IWebService>();
var lm = new LoginManagerWithMockAndStub(fakeLogger,fakeWebService);
lm.IsLoginOK("", "");
Isolate.Verify.WasCalledWithAnyArguments(() => fakeWebService.Write(""));
}
Open source
• FakeItEasy
• Moq
• NMock3
• nSubtitute
• Rhino
Mocks
Free
• MS Fakes
Commercial
• Isolator
• JustMock
Moq
45%
Rhino Mocks
23%
None
9%
FakeItEasy
6%
Nsubstitute
6%
Isolator
4%
Moles
2%
MS Fakes
2%
JustMocks
2%
Other
1%
http://osherove.com/blog/2012/5/4/annual-poll-which-isolation-framework-do-
you-use-if-any.html
Code Coverage
So, What is a good code coverage?
Source Control
Build Server
Commit
There you go
What’s new?
Build Agents
We automatically get
•Error reports & logs
•New version installer
•Help files
•More…
Build run at a Glance
How I failed unit testing my code
Unit testing is great!
Everything should be tested
I can test “almost” everything
Tests break all the time
Unit testing is a waste of time 
A good unit test should be:
• Easy to understand
• Trustworthy
• Robust
Trust Your Tests!
Trustworthy means deterministic
Problem
• I cannot re-run the exact same test if a test fails
Solution
• Don’t use Random in tests
– If you care about the values set them
– If you don’t care about the values put defaults
– Do not use Sleep & time related logic – fake it
• Use fake objects to “force” determinism into the test
• When possible avoid threading in tests.
Trustworthy also means not fragile
Ideally
A test would only fail if a bug was introduced
OR
Requirements changed
How to avoid fragile tests
• Don’t test private/internal (most of the time)
• Fake as little as necessary
• Test only one thing (most of the time)
Readable unit tests
Unit test intent should be clear!
1.What is being tested?
2.What is the desired outcome?
3.Why did test fail?
Learn to write “clean tests”
[Test]
public void CalculatorSimpleTest()
{
calc.ValidOperation = Calculator.Operation.Multiply;
calc.ValidType = typeof (int);
result = calc.Multiply(1, 3);
Assert.IsTrue(result == 3);
if (calc.ValidOperation == Calculator.Operation.Invalid)
{
throw new Exception("Operation should be valid");
}
}
Or suffer the consequences!
[Test]
public void CalculatorSimpleTest()
{
var calc = new Calculator();
calc.ValidOperation = Calculator.Operation.Multiply;
calc.ValidType = typeof (int);
var result = calc.Multiply(-1, 3);
Assert.AreEqual(result, -3);
calc.ValidOperation = Calculator.Operation.Multiply;
calc.ValidType = typeof (int);
result = calc.Multiply(1, 3);
Assert.IsTrue(result == 3);
if (calc.ValidOperation == Calculator.Operation.Invalid)
{
throw new Exception("Operation should be valid");
}
calc.ValidOperation = Calculator.Operation.Multiply;
calc.ValidType = typeof (int);
result = calc.Multiply(10, 3);
Assert.AreEqual(result, 30);
}
Writing a good unit test
[Test]
public void
Multiply_PassTwoPositiveNumbers_ReturnCorrectResult()
{
var calculator = CreateMultiplyCalculator();
var result = calculator.Multiply(1, 3);
Assert.AreEqual(result, 3);
}
So what about code reuse
Readability is more important than code reuse
• Create objects using factories
• Put common and operations in helper
methods
• Use inheritance – sparsely
Avoid logic in the test (if, switch etc.)
Problem
• Test is not readable
• Has several possible paths
• High maintain cost
Tests should be deterministic
Solution
• Split test to several tests – one for each
path
– If logic change it’s easier to update some of the
tests (or delete them)
• One Assert per test rule
How to start with unit tests
1. Test what you’re working on – right now!
2. Write tests to reproduce reported bug
3. When refactoring existing code – use unit tests to
make sure it still works.
4. Delete obsolete tests (and code)
5. All tests must run as part of CI build
Building unit tests correctly with visual studio 2013

Weitere ähnliche Inhalte

Was ist angesagt?

Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NETDror Helper
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat VU
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveAlvaro Videla
 
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 developmentStephen Fuqua
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleNoam Kfir
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeTerry Yin
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done RightBrian Fenton
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep DiveAlan Richardson
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 

Was ist angesagt? (20)

Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
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
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy Code
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep Dive
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 

Ähnlich wie Building unit tests correctly with visual studio 2013

Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMark Wragg
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1Albert Rosa
 
Introduzione allo Unit Testing
Introduzione allo Unit TestingIntroduzione allo Unit Testing
Introduzione allo Unit TestingStefano Ottaviani
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 

Ähnlich wie Building unit tests correctly with visual studio 2013 (20)

Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1
 
Introduzione allo Unit Testing
Introduzione allo Unit TestingIntroduzione allo Unit Testing
Introduzione allo Unit Testing
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 

Mehr von Dror Helper

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutDror Helper
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Dror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with awsDror Helper
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutDror Helper
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agileDror Helper
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreDror Helper
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET coreDror Helper
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot netDror Helper
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyDror Helper
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy codeDror Helper
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowDror Helper
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing toolsDror Helper
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developersDror Helper
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbgDror Helper
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 

Mehr von Dror Helper (20)

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with aws
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agile
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net core
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET core
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot net
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the ugly
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should know
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing tools
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developers
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 

Kürzlich hochgeladen

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Kürzlich hochgeladen (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

Building unit tests correctly with visual studio 2013

  • 1. Building Unit Tests correctly with VS 2013
  • 2. About.ME • Senior Consultant @CodeValue • Developing software (Professionally) since 2002 • Mocking code since 2008 • Test driven professional • Blogger: http://blog.drorhelper.com
  • 3. /* * You may think you know what the following code does. * But you dont. Trust me. * Fiddle with it, and youll spend many a sleepless * night cursing the moment you thought youd be clever * enough to "optimize" the code below. * Now close this file and go play with something else. */ // // Dear maintainer: // // Once you are done trying to 'optimize' this routine, // and have realized what a terrible mistake that was, // please increment the following counter as a warning // to the next guy: // // total_hours_wasted_here = 42 //
  • 4. //This code sucks, you know it and I know it. //Move on and call me an idiot later. http://stackoverflow.com/questions/184618/what-is-the- best-comment-in-source-code-you-have-ever-encountered We fear our code! //Abandon all hope ye who enter beyond this point //When I wrote this, only God and I understood what I was doing //Now, God only knows // I dedicate all this code, all my work, to my wife, Darlene, who will // have to support me and our three children and the dog once it gets // released into the public. //The following 1056 lines of code in this next method //is a line by line port from VB.NET to C#. //I ported this code but did not write the original code. //It remains to me a mystery as to what //the business logic is trying to accomplish here other than to serve as //some sort of a compensation shell game invented by a den of thieves. //Oh well, everyone wants this stuff to work the same as before. //I guess the devil you know is better than the devil you don't.
  • 5. “If we’re afraid to change the very thing we’ve created, we failed as professionals” Robert C. Martin
  • 7. “Code without tests is bad code... With tests, we can change the behavior of our code quickly and verifiably...” Michael Feathers - “Working effectively with legacy code”
  • 8. This is a unit test [Test] public void CheckPassword_ValidUser_ReturnTrue() { bool result = CheckPassword(“user”, “pass”); Assert.That(result, Is.True); } D
  • 9. This is also a unit test [TestMethod] public void CheckPassword_ValidUser_ReturnTrue() { bool result = CheckPassword(“user”, “pass”); Assert.IsTrue(result); } D
  • 10. A unit test is… 1. Tests specific functionality 2. Clear pass/fail criteria 3. Good unit test runs in isolation
  • 11. Unit testing is an iterative effort Unit testing is an iterative effort
  • 12. There’s more to unit tests then just “tests” Written by the developer who wrote the code Quick feedback Avoid stupid bugs Immune to regression Change your code without fear In code documentation
  • 13. 13 copyright 2008 trainologic LTD 13 One last reason You’re already Testing your code – manually So why not save the time?
  • 14. The cost of unit testing 120% 135% 115% 125% 0% 20% 40% 60% 80% 100% 120% 140% IBM: Drivers MS: Windows MS: MSN MS: VS Time taken to code a feature WithoutTDD Using TDD
  • 15. The value of unit testing 61% 38% 24% 9% 0% 20% 40% 60% 80% 100% 120% 140% IBM: Drivers MS: Windows MS: MSN MS: VS Using Test Driven Design Time To Code Feature Defect density of team Major quality improvement for minor time investment
  • 16. The cost of bugs 0 1 2 3 4 5 6 7 8 9 10 0% 20% 40% 60% 80% 100% Thousand$s %defectscreated Where does it hurt? % of Defects Introduced Cost to Fix a Defect The pain is here! This is too late…
  • 17. Supporting environment • The team • Development environment
  • 18. The Team • The team commitment is important • Learn from test reviews • Track results
  • 19. Tools of the trade Server Dev Machine Source Control Build Server Test Runner Code CoverageBuild Script Unit Testing Framework Isolation Framework
  • 20. Development environment • Make it easy to write and run tests – Unit test framework – Test Runner – Isolation framework • Know where you stand – Code coverage
  • 21. Unit testing frameworks • Create test fixtures • Assert results • Additional utilities • Usually provide command-line/GUI runner http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks
  • 22. [Test] public void AddTest() { var cut = new Calculator(); var result = cut.Add(2, 3); Assert.AreEqual(5, result); } This is not a real unit test
  • 23. Real code has dependencies Unit test Code under test Dependency Dependency
  • 24. The solution - Mocking Fake object(s) Unit test Code under test Dependency
  • 25. Isolation • Replace production logic with custom logic • We do this in order to – Focus the test on one class only – Test Interaction – Simplify Unit test writing
  • 26. What Mocking framework can do for you? • Create Fake objects • Set behavior on fake objects • Verify method was called • And more...
  • 27. [Test] public void IsLoginOK_LoggerThrowsException_CallsWebService() { var fakeLogger = Isolate.Fake.Instance<ILogger>(); Isolate .WhenCalled(() => fakeLogger.Write("")) .WillThrow(new LoggerException()); var fakeWebService = Isolate.Fake.Instance<IWebService>(); var lm = new LoginManagerWithMockAndStub(fakeLogger,fakeWebService); lm.IsLoginOK("", ""); Isolate.Verify.WasCalledWithAnyArguments(() => fakeWebService.Write("")); }
  • 28. Open source • FakeItEasy • Moq • NMock3 • nSubtitute • Rhino Mocks Free • MS Fakes Commercial • Isolator • JustMock
  • 30. Code Coverage So, What is a good code coverage?
  • 31. Source Control Build Server Commit There you go What’s new? Build Agents We automatically get •Error reports & logs •New version installer •Help files •More…
  • 32. Build run at a Glance
  • 33. How I failed unit testing my code Unit testing is great! Everything should be tested I can test “almost” everything Tests break all the time Unit testing is a waste of time 
  • 34. A good unit test should be: • Easy to understand • Trustworthy • Robust Trust Your Tests!
  • 35. Trustworthy means deterministic Problem • I cannot re-run the exact same test if a test fails Solution • Don’t use Random in tests – If you care about the values set them – If you don’t care about the values put defaults – Do not use Sleep & time related logic – fake it • Use fake objects to “force” determinism into the test • When possible avoid threading in tests.
  • 36. Trustworthy also means not fragile Ideally A test would only fail if a bug was introduced OR Requirements changed
  • 37. How to avoid fragile tests • Don’t test private/internal (most of the time) • Fake as little as necessary • Test only one thing (most of the time)
  • 38. Readable unit tests Unit test intent should be clear! 1.What is being tested? 2.What is the desired outcome? 3.Why did test fail?
  • 39. Learn to write “clean tests” [Test] public void CalculatorSimpleTest() { calc.ValidOperation = Calculator.Operation.Multiply; calc.ValidType = typeof (int); result = calc.Multiply(1, 3); Assert.IsTrue(result == 3); if (calc.ValidOperation == Calculator.Operation.Invalid) { throw new Exception("Operation should be valid"); } }
  • 40. Or suffer the consequences! [Test] public void CalculatorSimpleTest() { var calc = new Calculator(); calc.ValidOperation = Calculator.Operation.Multiply; calc.ValidType = typeof (int); var result = calc.Multiply(-1, 3); Assert.AreEqual(result, -3); calc.ValidOperation = Calculator.Operation.Multiply; calc.ValidType = typeof (int); result = calc.Multiply(1, 3); Assert.IsTrue(result == 3); if (calc.ValidOperation == Calculator.Operation.Invalid) { throw new Exception("Operation should be valid"); } calc.ValidOperation = Calculator.Operation.Multiply; calc.ValidType = typeof (int); result = calc.Multiply(10, 3); Assert.AreEqual(result, 30); }
  • 41. Writing a good unit test [Test] public void Multiply_PassTwoPositiveNumbers_ReturnCorrectResult() { var calculator = CreateMultiplyCalculator(); var result = calculator.Multiply(1, 3); Assert.AreEqual(result, 3); }
  • 42. So what about code reuse Readability is more important than code reuse • Create objects using factories • Put common and operations in helper methods • Use inheritance – sparsely
  • 43. Avoid logic in the test (if, switch etc.) Problem • Test is not readable • Has several possible paths • High maintain cost
  • 44. Tests should be deterministic Solution • Split test to several tests – one for each path – If logic change it’s easier to update some of the tests (or delete them) • One Assert per test rule
  • 45. How to start with unit tests 1. Test what you’re working on – right now! 2. Write tests to reproduce reported bug 3. When refactoring existing code – use unit tests to make sure it still works. 4. Delete obsolete tests (and code) 5. All tests must run as part of CI build

Hinweis der Redaktion

  1. Taken from http://research.microsoft.com/en-us/projects/esm/nagappan_tdd.pdf Realizing quality improvement through test driven development: results and experiences of four industrial teams Published online: 27 February 2008
  2. Explain about good places to start using unit tests