SlideShare a Scribd company logo
Dror Helper
drorh@codevalue.net | http://blog.drorhelper.com | @dhelper
Building unit tests - correctly
About.Me
• Senior consultant @CodeValue
• Developing software (professionally) since 2002
• Clean coder
• Test Driven Developer
• 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.
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
[@Test]
public void CheckPassword_ValidUser_ReturnTrue()
{
boolean result = CheckPassword(“user”, “pass”);
Assert.IsTrue(result);
}
D
A unit test is…
A method (Code)
that
tests specific functionality,
Has
clear pass/fail criteria
and
runs in isolation
Unit testing is an iterative effort
Unit testing is an iterative effort
Supporting environment
• The team
• Development environment
The Team
• The team commitment is important
• Learn from test reviews
• Track results
Server
Dev Machine
Source ControlBuild Server
Test Runner
Code
Coverage
Build Script
Unit Testing
Framework
Isolation
Framework
Tools of the trade
Build Failed!
Unit tests without a CI server are a
waste of time - if you're running all
of the tests all of the time locally
you're a better man then me
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
• Test fixtures
• Assertions
• Runners
• More…
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(""));
}
@Test
public void testBookAddtion(){
string isbn = "1234";
TitleCatalog fakeCatalog = mock(TitleCatalog.class);
Book book = new Book("Moby dick", isbn);
when(fakeCatalog.getTitleByISBN(anystring())).thenReturn(book);
BookInventory inventory = new BookInventory();
inventory.registerCopy(isbn, "1");
verify(fakeCatalog, times(1)).getTitleByISBN(isbn);
}
Code Coverage
So, What is a good code coverage?
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!
Ideally
A test would only fail if a bug was introduced
OR
Requirements changed
Be explicit and deterministic
Problem
• I cannot re-run the exact same test if a test fails
Solution
• Don’t use Random elements 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.
Assert.IsTrue(user.Equals(expected)Assert.AreEqual(expected, user)
Test naming
Test names should be descriptive and explicit.
Test names should express a specific requirement
I like to use:
Method_Scenario_Expected
a.k.a
UnitOfWork_StateUnderTest_ExpectedBehavior
Public void Sum_NegativeNumberAs1stParam_ExceptionThrown()
Public void Sum_simpleValues_Calculated ()
Public void Parse_SingleToken_ReturnsEqualTokenValue ()
http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html
Writing a good unit test
[Test]
public void
Multiply_PassTwoPositiveNumbers_ReturnCorrectResult()
{
var calculator = CreateMultiplyCalculator();
var result = calculator.Multiply(1, 3);
Assert.AreEqual(result, 3);
}
It’s an over-specification that creates fragile tests
Test the “what”, not the “How”
• So that refactoring won’t break your tests
• Testing private methods is a smell!
Avoid testing private methods
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)
Can you spot the problem in these Tests?
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.)
• Test is not readable
• Has several possible paths
• High maintain cost
@Test
public void Test1(){
// Here be code
switch(i){
case(a):
...
break;
case(b):
...
break;
default:
Assert.Fail();
}
}
try
{
Assert.IsNull(…);
Assert.AreEqual(…);
}
catch (Exception e)
{
thrownException = e;
}
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);
}
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.
1. All tests must run as part of CI build
Dror Helper
C: 972.05.7668543
e: drorh@codevalue.net
B: blog.drorhelper.com

More Related Content

What's hot

Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
IT Weekend
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
Daniel Kolman
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven Smith
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
Salesforce Developers
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
NexThoughts Technologies
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Tomek Kaczanowski
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
David Rodenas
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
Ken Kousen
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Mockito intro
Mockito introMockito intro
Mockito intro
Jonathan Holloway
 
Spock framework
Spock frameworkSpock framework
Spock framework
Djair Carvalho
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing Techniques
David Rodenas
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
Tomek Kaczanowski
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net core
Rajesh Shirsagar
 

What's hot (20)

Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing Techniques
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net core
 

Viewers also liked

Drawing 101
Drawing 101Drawing 101
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
Dror Helper
 
Bdd - history and myths
Bdd - history and mythsBdd - history and myths
Bdd - history and myths
Seb Rose
 
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
Dror Helper
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Thomas Weller
 
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java CodeJava Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
Edson Yanaga
 

Viewers also liked (6)

Drawing 101
Drawing 101Drawing 101
Drawing 101
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Bdd - history and myths
Bdd - history and mythsBdd - history and myths
Bdd - history and myths
 
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
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java CodeJava Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code
 

Similar to Building unit tests correctly

Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
Dror Helper
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
Giovanni Scerra ☃
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
Mark Wragg
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
FalafelSoftware
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
Alex Kavanagh
 
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
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
Mats Bryntse
 
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
michael.labriola
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
Ben Hall
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven Smith
 
Introduzione allo Unit Testing
Introduzione allo Unit TestingIntroduzione allo Unit Testing
Introduzione allo Unit Testing
Stefano 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 Development
All Things Open
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
ericholscher
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
HamletDRC
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
ICS
 

Similar to Building unit tests correctly (20)

Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
 
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)
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
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
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
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
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 

More from Dror Helper

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
Dror 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 about
Dror 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 code
Dror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
Dror 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 aws
Dror 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 about
Dror 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 agile
Dror 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 core
Dror 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 core
Dror 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 net
Dror 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 about
Dror 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 ugly
Dror Helper
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
Dror Helper
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing tools
Dror Helper
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developers
Dror Helper
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
Dror Helper
 
Designing with tests
Designing with testsDesigning with tests
Designing with tests
Dror Helper
 
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
Dror Helper
 
Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
Dror Helper
 

More from 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
 
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
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
 
Designing with tests
Designing with testsDesigning with tests
Designing with tests
 
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
 
Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
 

Recently uploaded

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 

Recently uploaded (20)

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 

Building unit tests correctly

  • 1. Dror Helper drorh@codevalue.net | http://blog.drorhelper.com | @dhelper Building unit tests - correctly
  • 2. About.Me • Senior consultant @CodeValue • Developing software (professionally) since 2002 • Clean coder • Test Driven Developer • 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.
  • 6. “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”
  • 7. This is a unit test [Test] public void CheckPassword_ValidUser_ReturnTrue() { bool result = CheckPassword(“user”, “pass”); Assert.That(result, Is.True); } D
  • 8. This is also a unit test [@Test] public void CheckPassword_ValidUser_ReturnTrue() { boolean result = CheckPassword(“user”, “pass”); Assert.IsTrue(result); } D
  • 9. A unit test is… A method (Code) that tests specific functionality, Has clear pass/fail criteria and runs in isolation
  • 10. Unit testing is an iterative effort Unit testing is an iterative effort
  • 11. Supporting environment • The team • Development environment
  • 12. The Team • The team commitment is important • Learn from test reviews • Track results
  • 13. Server Dev Machine Source ControlBuild Server Test Runner Code Coverage Build Script Unit Testing Framework Isolation Framework Tools of the trade Build Failed!
  • 14. Unit tests without a CI server are a waste of time - if you're running all of the tests all of the time locally you're a better man then me
  • 15. Development environment • Make it easy to write and run tests – Unit test framework – Test Runner – Isolation framework • Know where you stand – Code coverage
  • 16. Unit testing frameworks • Test fixtures • Assertions • Runners • More… http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks
  • 17. [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
  • 18. Real code has dependencies Unit test Code under test Dependency Dependency
  • 19. The solution - Mocking Fake object(s) Unit test Code under test Dependency
  • 20. 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
  • 21. What Mocking framework can do for you? • Create Fake objects • Set behavior on fake objects • Verify method was called • And more...
  • 22. [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("")); }
  • 23. @Test public void testBookAddtion(){ string isbn = "1234"; TitleCatalog fakeCatalog = mock(TitleCatalog.class); Book book = new Book("Moby dick", isbn); when(fakeCatalog.getTitleByISBN(anystring())).thenReturn(book); BookInventory inventory = new BookInventory(); inventory.registerCopy(isbn, "1"); verify(fakeCatalog, times(1)).getTitleByISBN(isbn); }
  • 24. Code Coverage So, What is a good code coverage?
  • 25. 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 
  • 26. A good unit test should be: • Easy to understand • Trustworthy • Robust Trust Your Tests!
  • 27. Ideally A test would only fail if a bug was introduced OR Requirements changed
  • 28. Be explicit and deterministic Problem • I cannot re-run the exact same test if a test fails Solution • Don’t use Random elements 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.
  • 30. Test naming Test names should be descriptive and explicit. Test names should express a specific requirement I like to use: Method_Scenario_Expected a.k.a UnitOfWork_StateUnderTest_ExpectedBehavior Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_simpleValues_Calculated () Public void Parse_SingleToken_ReturnsEqualTokenValue () http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html
  • 31. Writing a good unit test [Test] public void Multiply_PassTwoPositiveNumbers_ReturnCorrectResult() { var calculator = CreateMultiplyCalculator(); var result = calculator.Multiply(1, 3); Assert.AreEqual(result, 3); }
  • 32. It’s an over-specification that creates fragile tests Test the “what”, not the “How” • So that refactoring won’t break your tests • Testing private methods is a smell! Avoid testing private methods
  • 33. 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)
  • 34. Can you spot the problem in these Tests?
  • 35. 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
  • 36. Avoid logic in the test (if, switch etc.) • Test is not readable • Has several possible paths • High maintain cost @Test public void Test1(){ // Here be code switch(i){ case(a): ... break; case(b): ... break; default: Assert.Fail(); } } try { Assert.IsNull(…); Assert.AreEqual(…); } catch (Exception e) { thrownException = e; }
  • 37. 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"); } }
  • 38. 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); }
  • 39. 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. 1. All tests must run as part of CI build
  • 40. Dror Helper C: 972.05.7668543 e: drorh@codevalue.net B: blog.drorhelper.com

Editor's Notes

  1. Ask them – why is the test name so important?
  2. Explain about good places to start using unit tests