SlideShare a Scribd company logo
A Tester’s Guide to
Unit Testing
https://github.com/CraigRisiAG
About Me
Agenda
1. Why
2. What
3. How
Why Unit
tests?
Collaboration
Testers guide to unit testing
Reducing Duplication
Reducing Duplication
Req:
Any number entered into the text box between 1-10 must provide a valid response
Alphanumeric, spaces, etc.
Reducing Duplication
What if your code was as follows:
Int i= convert.ToInt32(txtMyTextBox.Text)
If i >= 1 and i <= 10
Print (“Valid”)
Else
Print (“Invalid”)
Get
Defects
Early
Documenting code and improved traceability
Improved
Ideation
What Should
be Unit
Tested
Entry and exit points
Isolated functionality
Boundary value validations
Clear data permutations
Security and performance
Good Unit Tests
FAST ISOLATED REPEATABLE SELF-
CHECKING
TIMELY
Aspects of Unit Testing
Test Set Up Mocking Assertions Runners
Reporting
and Results
Naming Your Tests
- Requirement
- Method / Cass under test
- Expected Result
- Input or State
Map_DefaultConstructorShouldCreateEmptyGisMap()
ShouldAlwaysDelegateXMLCorrectlyToTheCustomHand
lers()
Dog_Object_Should_Eat_Homework_Object_When_Hung
ry()
Arranging Your Tests
Arrange your objects,
by creating and setting
them up in a way that
readies your code for
the intended test
Act on an object
Assert that something
is as expected
Write
Minimally
Passing Tests
FOCUS ON BEHAVIOUR AND
NOT JUST COVERAGE
Avoid Logic in
Tests
Use Helper
Methods
Avoid
Multiple
Asserts
How
Types of
Assertions
assertArrayEquals()
assertEquals()
assertTrue() + assertFalse()
assertNull() + assertNotNull()
assertSame() + assertNotSame()
assertThat()
Matchers
Core
any() Matches anything
is() A matcher that checks if the
given objects are equal.
describedAs() Adds a descrption to a Matcher
Logical
allOf() Takes an array of matchers, and
all matchers must match the
target object.
anyOf() Takes an array of matchers, and
at least one of the matchers
must report that it matches the
target object.
not() Negates the output of the
previous matcher.
Object
equalTo() A matcher that checks if the
given objects are equal.
instanceOf() Checks if the given object is of
type X or is compatible with type
X
notNullValue() +
nullValue()
Tests whether the given object is
null or not null.
sameInstance() Tests if the given object is the
Testing For Exceptions
@Test(expected =
IllegalArgumentException.class)
public void testForExceptions1() {
MyUnit myUnit = new MyUnit();
myUnit.throwIllegalArgumentException();
}
@Test
public void testForExceptions2() {
MyUnit myUnit = new MyUnit();
try{
myUnit.throwIllegalArgumentException();
fail("expected IllegalArgumentException");
} catch(IllegalArgumentException e){
//ignore, this exception is expected.
}
Stubs, Mocks, and Proxies
unit test --> stub
unit test --> unit --> stub
unit test asserts on results and state
of unit
unit test --> mock
unit test --> unit --> mock
unit test asserts on result and state of unit
unit test asserts on the methods called on
mock
unit test --> collaborator
unit test --> proxy
unit test --> unit --> proxy --> collaborator
unit test asserts on result and state of unit
unit test asserts on methods called on proxy
Testable and
Untestable
Code
public static string GetTimeOfDay()
{
DateTime time = DateTime.Now;
if (time.Hour >= 0 && time.Hour < 6)
{
return "Night";
}
if (time.Hour >= 6 && time.Hour < 12)
{
return "Morning";
}
if (time.Hour >= 12 && time.Hour < 18)
{
return "Afternoon";
}
return "Evening";
}
[TestMethod]
public void GetTimeOfDay_At6AM_ReturnsMorning()
{
try
{
// Setup: change system time to 6 AM
...
// Arrange phase is empty: testing static method, nothing to initialize
// Act
string timeOfDay = GetTimeOfDay();
// Assert
Assert.AreEqual("Morning", timeOfDay);
}
finally
{
// Teardown: roll system time back
...
}
}
public void GetTimeOfDay_For6AM_ReturnsMorning()
{
// Arrange phase is empty: testing static method, nothing to initialize
// Act
string timeOfDay = GetTimeOfDay(new DateTime(2015, 12, 31, 06, 00, 00));
// Assert
Assert.AreEqual("Morning", timeOfDay);
}
Another
Example
package com.acme.pizza
import scala.collection.mutable.ArrayBuffer
class Pizza {
private val toppings = new ArrayBuffer[Topping]
def addTopping (t: Topping) { toppings += t}
def removeTopping (t: Topping) { toppings -= t}
def getToppings = toppings.toList def boom { throw
new Exception("Boom!") }
}
package com.acme.pizza
case class Topping(name: String)
package com.acme.pizza
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
class PizzaTests extends FunSuite with BeforeAndAfter {
var pizza: Pizza = _
before {
pizza = new Pizza
}
test("new pizza has zero toppings") {
assert(pizza.getToppings.size == 0)
}
test("adding one topping") {
pizza.addTopping(Topping("green olives"))
assert(pizza.getToppings.size === 1)
}
// mark that you want a test here in the future
test ("test pizza pricing") (pending)
}
Let’s Get
Into Some
Code
https://github.com/CraigRisiAG
Questions

More Related Content

PDF
C++ Unit Test with Google Testing Framework
ODP
Grails unit testing
PPT
Qtp manual testing tutorials by QuontraSolutions
PDF
Test Driven Development
ODP
Good Practices On Test Automation
ODP
Testing in-groovy
PPT
Google mock for dummies
PDF
Effective Unit Test Style Guide
C++ Unit Test with Google Testing Framework
Grails unit testing
Qtp manual testing tutorials by QuontraSolutions
Test Driven Development
Good Practices On Test Automation
Testing in-groovy
Google mock for dummies
Effective Unit Test Style Guide

What's hot (19)

PPT
Introduzione al TDD
PPTX
Pragmatic unittestingwithj unit
PDF
Unit test-using-spock in Grails
PPTX
Grails Spock Testing
PPTX
TestNG vs Junit
PPTX
Appium TestNG Framework and Multi-Device Automation Execution
PDF
"How keep normal blood pressure using TDD" By Roman Loparev
KEY
Unit Test Your Database
PPT
Python testing
PDF
Pyconie 2012
PDF
Developer Test - Things to Know
PPT
Working Effectively with Legacy Code (draft)
PPTX
Dev labs alliance top 20 testng interview questions for sdet
PDF
TestNG vs. JUnit4
KEY
Inside PyMongo - MongoNYC
PPT
PDF
JUnit Kung Fu: Getting More Out of Your Unit Tests
PPTX
Test Driven Development: Why I hate it; but secretly love it.
PPTX
Unit testing
Introduzione al TDD
Pragmatic unittestingwithj unit
Unit test-using-spock in Grails
Grails Spock Testing
TestNG vs Junit
Appium TestNG Framework and Multi-Device Automation Execution
"How keep normal blood pressure using TDD" By Roman Loparev
Unit Test Your Database
Python testing
Pyconie 2012
Developer Test - Things to Know
Working Effectively with Legacy Code (draft)
Dev labs alliance top 20 testng interview questions for sdet
TestNG vs. JUnit4
Inside PyMongo - MongoNYC
JUnit Kung Fu: Getting More Out of Your Unit Tests
Test Driven Development: Why I hate it; but secretly love it.
Unit testing
Ad

Similar to Testers guide to unit testing (20)

PDF
Unit Testing - The Whys, Whens and Hows
PPT
Test Driven Development with PHPUnit
PDF
DSR Testing (Part 1)
PDF
Token Testing Slides
PDF
Unit testing with JUnit
PPTX
TDD Training
PDF
Unit testing - A&BP CC
PPT
Unit testing with Spock Framework
PDF
Shift-Left Testing: QA in a DevOps World by David Laulusa
PPTX
Test driven development in .Net - 2010 + Eclipse
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PDF
Testing for software engineers
PDF
MT_01_unittest_python.pdf
PDF
GTAC 2014: What lurks in test suites?
PPTX
Qunit Java script Un
PDF
An introduction to unit testing
PDF
Javascript Unit Testing
PPTX
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
PPT
Test Driven
PPTX
Building unit tests correctly with visual studio 2013
Unit Testing - The Whys, Whens and Hows
Test Driven Development with PHPUnit
DSR Testing (Part 1)
Token Testing Slides
Unit testing with JUnit
TDD Training
Unit testing - A&BP CC
Unit testing with Spock Framework
Shift-Left Testing: QA in a DevOps World by David Laulusa
Test driven development in .Net - 2010 + Eclipse
We Are All Testers Now: The Testing Pyramid and Front-End Development
Testing for software engineers
MT_01_unittest_python.pdf
GTAC 2014: What lurks in test suites?
Qunit Java script Un
An introduction to unit testing
Javascript Unit Testing
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
Test Driven
Building unit tests correctly with visual studio 2013
Ad

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
AI in Product Development-omnex systems
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
L1 - Introduction to python Backend.pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Essential Infomation Tech presentation.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Introduction to Artificial Intelligence
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
System and Network Administration Chapter 2
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
System and Network Administraation Chapter 3
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
AI in Product Development-omnex systems
How to Choose the Right IT Partner for Your Business in Malaysia
L1 - Introduction to python Backend.pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Understanding Forklifts - TECH EHS Solution
Adobe Illustrator 28.6 Crack My Vision of Vector Design
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Which alternative to Crystal Reports is best for small or large businesses.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Essential Infomation Tech presentation.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Introduction to Artificial Intelligence
Wondershare Filmora 15 Crack With Activation Key [2025
Softaken Excel to vCard Converter Software.pdf
Design an Analysis of Algorithms II-SECS-1021-03
System and Network Administration Chapter 2
Reimagine Home Health with the Power of Agentic AI​
System and Network Administraation Chapter 3

Testers guide to unit testing