SlideShare a Scribd company logo
1 of 59
TEST-DRIVEN
SOFTWARE DEVELOPMENT
JOHN BLUM
2015 JUNE 17
AGENDA
 Misconceptions
 Why Test
 Types of Tests
 What & How to Test
 Using JUnit, Mockito and MultithreadedTC
 Best Practices
 Final Thoughts
 QA
“No amount of testing can prove a software right,
but a single test can prove a software wrong.”
– Amir Ghahrai
MISCONCEPTIONS
Testing is a Quality Engineer’s (QE/SDET) job
 Quality Assurance (QA) is everyone’s responsibility
MISCONCEPTIONS
Automated tests are unnecessary if I manually test and
debug my code
 Testing is not a replacement for debuggers and other
development tools either (e.g. Profilers, FindBugs, etc)
Not possible to automate all tests
 Difficult when the software architecture & design is flawed
Developer tests are “Unit Tests”
JUnit is a “Unit Test” framework
 JUnit is a framework facilitating the development and
execution of automated tests
 Used in Integration and Functional (Acceptance) testing
MISCONCEPTIONS
Software is correct when there is 100% test coverage and no
FindBugs (CheckStyle, PMD) errors
 A bug occurs when the software fails to function properly in a
prescribed manner
 A defect occurs after the software is used in a unintentional
way and behaves unexpectedly
MISCONCEPTIONS
"Not everything that can be counted counts and not
everything that counts can be counted."
- Albert Einstein
Why do software engineers write tests?
Or…
Why don’t software engineers write tests?
TO TEST OR NOT TO TEST?
Time Constraints
 Time-based vs. Functional-based releases
 Quantity (Scope) over Quality (Less is More)
(Cultural) Responsibility
Laziness, Ignorance, Fear
 Not detail-oriented
Verifies software is behaviorally correct and functionally
complete
 “Definition of Done” (DoD)
 No “works on my box” arguments (we don’t ship your box)
Ensures functional integration
 Your code plays nicely with others
Increases regression coverage
 Tests in a suite is money in the bank; ensure what worked
yesterday, works today and will work tomorrow
WHY TEST
WHY TEST
Functional/Releasable
Maintainable
Sustainable
TESTS
WHY TEST
Tests are a form of feedback
 Developers get immediate feedback on changes to code by
running the test(s) to ensure the “contract is upheld”
Tests are a form of documentation
 Demonstrates how the code (e.g. API) is properly used
WHY TEST
Focus on the problem that needs to be solved
 Tests are a “contract for deliverables”; avoid “scope creep”
 Tests limits “over-engineering” (future coders)
 TDD
Testing gives developers confidence in their changes
 And more importantly… to “refactor” and make changes
 To learn
Testing encourages smaller, more frequent commits
 And by extension, “releasable” code
WHY TEST
Testing identifies design flaws
 Hard to test code is flawed and a sure sign of technical debt
Untested code triggers a domino effect
 User becomes the Tester leading to undesirable, costly
“workarounds” leading to technical debt leading to other bugs
leading to more serious issues like data corruption and so on
“Don’t be that guy!”
(the guy who doesn’t test his code)
Why are there different types of tests?
TYPES OF TESTS
Different types of tests cover different “aspects” (concerns)
of the software under test…
 Different test types serve to “close the feedback loop” at
different intervals in the software development lifecycle…
TYPES OF TESTS
Unit Tests
 Tests a single, contained “unit” of functionality
 Objects adhere to their contract (specified by the “interface”)
 Class invariants are upheld as object state changes
Integration Tests
 Tests interactions between “collaborators”
 Actual “dependencies” used
TYPES OF TESTS
Functional, Acceptance-based Tests (End-To-End)
 Tests user/software interaction based on predefined workflows
(Use Cases) and Functional Requirements
 Acceptance Tests are defined by Acceptance Criteria (based
on Functional Requirements)
 Usability Testing (UAT)
Performance-based Tests
 load/stress testing
TYPES OF TESTS
http://googletesting.blogspot.com/2015/04/just-say-no-to-more-end-to-end-tests.html
“What” and “How” do you test?
WHAT TO TEST
Test everything (or as much as you can)!
 Constructors, methods, input, output, Exception conditions, all
code paths, invariants/object state, thread safety…
 Test the unexpected
Don’t make assumptions; verify with tests
 “It is not only what you don’t know that gets you in trouble, it is
what you thought you knew that just isn’t so!”
ANATOMY OF A TEST
Arrange
Act
Assert (Verify)
How-To Unit Test Demonstration
JUnit
JUNIT - ASSERTIONS
With assertThat(..)
 More Readable (natural/DSL) and Strongly-typed
 Assert subject (actual), verb, object (expected)
Example
assertThat(x is(3)); // assert “x is 3” or “x == 3”
vs...
assertEquals(3, x); // assert “equals 3 x” or “== 3 x”
Examples…
JUNIT - ASSUMPTIONS
Useful to make test dependencies (pre-conditions) explicit
 Examples: Environment Configuration, Resource Availability
With assumeTrue(..) (JUnit) or the DSL-friendly
assumeThat(..) (Hamcrest)
Examples…
JUNIT - EXCEPTIONS
With Try/Catch Idiom (JUnit 3.x)
With @Test(expected = Class<? extends Throwable>)
With ExpectedException Rule (JUnit 4)
Examples…
JUNIT - PARAMETERIZED
Parameterized test class instances created for the cross-product of test case
methods and test data elements.
 Useful for large volume of data
Run test class with the Parameterized Test Runner.
@RunWith(Parameterized.class)
public class ParameterizedTest {
@Parameters
public Iterable<Object[]> data = …;
public ParameterizedTest(..) {
}
}
Example…
JUNIT - RULES
ErrorCollector – allows execution of test to continue after the first problem is
encountered (Fail-Fast!)
ExpectedException – specify expected error conditions in test
ExternalResource – setup external resource (File, Socket, Database Connection, …)
TemporaryFolder – creation of files and folders that are deleted after test case
(method) finishes
TestName – captures the name of a test inside test methods
Timeout – applies same timeout to all test case methods in test class
Example…
JUNIT - TIMEOUTS
With @Test(timeout = ms)
@Test(timeout = 500)
public void testWithTimeout() {
}
With Timeout Rule…
public class TestsWithGlobalTimeout {
@Rule
public Timeout globalTimeout = Timeout.seconds(20);
}
Example…
JUNIT – FIXTURES
With @BeforeClass, @Before, @AfterClass, @After
With (optionally) @ClassRule and ExternalResource Rule
Examples…
JUNIT – EXECUTION ORDER
By design, JUnit does not specify test execution order
 Test case method invocation determined by Reflection API
 JDK 7 is more or less random
Use MethodSorters and @FixMethodOrder annotation
 E.g. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
Example…
JUNIT – AGGREGATION
Enables suites of tests to be grouped and built from existing
test classes using…
@RunWith(Suite.class)
@Suite.SuiteClasses({
ClientCommandsTest.class,
DiskStoreCommandsTest.class,
FunctionCommandsTest.class,
IndexCommandsTest.class,
MemberCommandsTest.class,
QueueCommandsTest.class,
…
})
public class GfshTestSuite {
}
JUNIT – ADDITIONAL FEATURES
 Test Runners (e.g. Categories, Parameterized,
MockitoJUnitRunner, SpringJUnit4ClassRunner)
 Categories (e.g. UnitTests, IntegrationTests,
AcceptanceTests)
 Theories – more flexible/expressive assertions combined with ability
to state assumptions
 Rule Chaining – with RuleChain to control test rule ordering
 Multithreaded Code and Concurrency (support)
 Eh, MultithreadedTC is better!
JUNIT – EXTENSIONS
HttpUnit - http://httpunit.sourceforge.net/
HtmlUnit - http://htmlunit.sourceforge.net/
Selenium - http://www.seleniumhq.org/
JUext - http://junitext.sourceforge.net/
http://www.tutorialspoint.com/junit/junit_extensions.htm
Unit Testing with Mocks
using Mockito
Why use Mocks in testing?
UNIT TESTING WITH MOCKS
Because… “If you can’t make it, fake it”
Mocks ensure focus is on the Subject (“unit”) of the test by
mocking interactions with Collaborators to verify appropriate
behavior of the Subject, not the Collaborator(s)
 Mocked Collaborators are “expected to behave” according to
their contract
Promotes programming to interfaces and delineation of
functional responsibility across teams
How-To Mock Demonstration
Mockito
MOCKITO - CALLBACKS
With…
when(mock.doSomething(..)).thenAnswer(new Answer<Object>() {
@Override public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Integer intArg = invocation.getArgumentAt(0, Integer.class);
Object mock = invocation.getMock();
return …;
}
));
MOCKITO - STUBBING
Consecutive calls…
when(mock.getSomething(..)).thenReturn(“one”, “two”, “three”);
MOCKITO – ORDER
VERIFICATION
With…
InOrder inOrderVerifier = inOrder(firstMock, secondMock);
inOrderVerifier.verify(firstMock, times(2)).doSomething(..);
inOrderVerifier.verify(secondMock, atLeastOne()).doSomething(..);
MOCKITO - SPIES
Possible answer to… “Do not mock code you don’t own”
List<Object> list = new ArrayList<Object>();
List<?> spy = spy(list);
list.add(“one”);
verify(spy, times(1)).add(eq(“one”));
MOCKITO - LIMITATIONS
Cannot mock final (non-extensible) classes or final (non-
overridable) methods.
Cannot stub Spies in the usual way…
List<?> spy = spy(new ArrayList());
// Impossible – actual method is called so spy.get(0) throws
IndexOutOfBoundsException
when(spy.get(0).thenReturn(“TEST”);
// Use doReturn(..) to do stubbing
doReturn(“TEST”).when(spy).get(0);
??
MOCKITO - EXTENSIONS
PowerMock – enables mocking of static methods, constructors,
final classes and methods, private methods, removal of static
initializers plus more…
 Uses custom ClassLoader
 https://code.google.com/p/powermock/
MultithreadedTC
(sorry)
BEST PRACTICES
Test one thing at a time (per test case)
 Single code path; one interaction with a collaborator; one user
story, and so on…
 Prefer more test cases rather than bloated test cases
Tests should run quickly providing immediate feedback
* 10-minute build
Tests should fail-fast
Tests should be 100% reliable
BEST PRACTICES
Please do not ignore (@Ignore) or comment out failing tests!
 Understand test failures, take responsibility, fix the failures and
don’t commit until all tests pass
Write a test before fixing a bug
 Without a test it is problematic to verify the fix
BEST PRACTICES
Test cases should be independent and execution order
should not matter
Use meaningful test case (method) names
BEST PRACTICES
Ideally, interchanging Mocks with actual Collaborators does
not require any test changes
BEST PRACTICES
Follow the AAA Testing Pattern
 Arrange -> Act -> Assert
Follow the commit pattern…
1. Update, Create Topic Branch
2. Make Changes
3. Run Tests (if failure(s), goto 2)
4. Update (if changes, goto 3)
5. Merge & Commit
FINAL TESTING THOUGHT
Remember…
There is “good code” and then there is “tested code”.
REFERENCES
http://www.softwaretestinghelp.com/types-of-software-testing/
http://junit.org/
http://mockito.org/
http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
https://code.google.com/p/powermock/
https://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html
http://googletesting.blogspot.com/2015/04/just-say-no-to-more-end-to-end-tests.html
https://zeroturnaround.com/rebellabs/olegs-half-smart-hacks-put-a-timestamp-on-
ignore-with-java-8s-new-date-and-time-api/
http://www.codeaffine.com/2013/11/18/a-junit-rule-to-conditionally-ignore-tests/
REFERENCES
https://github.com/codeprimate-software/test-driven-development
Questions

More Related Content

What's hot

What's hot (20)

Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Gherkin /BDD intro
Gherkin /BDD introGherkin /BDD intro
Gherkin /BDD intro
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Junit
JunitJunit
Junit
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
05 junit
05 junit05 junit
05 junit
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 

Viewers also liked

Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with CucumberBrandon Keepers
 
Java Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionJava Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionLemi Orhan Ergin
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Zohirul Alam Tiemoon
 
Sondeo exploratorio
Sondeo exploratorioSondeo exploratorio
Sondeo exploratorioraisarueda
 
Prospective clinical trial of traction device-assisted endoscopic submucosal ...
Prospective clinical trial of traction device-assisted endoscopic submucosal ...Prospective clinical trial of traction device-assisted endoscopic submucosal ...
Prospective clinical trial of traction device-assisted endoscopic submucosal ...Goto Pablo
 
Try hard until you suceed (1)
Try hard until you suceed (1)Try hard until you suceed (1)
Try hard until you suceed (1)nikkinikhita
 
How To Choose Perfect Hair Color ?
How To Choose Perfect Hair Color ?How To Choose Perfect Hair Color ?
How To Choose Perfect Hair Color ?Torontohairsalons
 
FEA - Simple Analysis example
FEA - Simple Analysis exampleFEA - Simple Analysis example
FEA - Simple Analysis exampleMichael Davis
 
Увеличение личных продаж от 3 раз и выше
Увеличение личных продаж от 3 раз и вышеУвеличение личных продаж от 3 раз и выше
Увеличение личных продаж от 3 раз и вышеАртур Хазеев
 
Matthew Hartman cv.docx (1)
Matthew Hartman cv.docx (1)Matthew Hartman cv.docx (1)
Matthew Hartman cv.docx (1)matthew hartman
 
Steps to the college process
Steps to the college processSteps to the college process
Steps to the college processHeidi Wilson
 
White Genocide In South Africa - Here Are The Names
White Genocide In South Africa - Here Are The NamesWhite Genocide In South Africa - Here Are The Names
White Genocide In South Africa - Here Are The Names1guestupington
 

Viewers also liked (20)

Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
 
Java Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionJava Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second Version
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
 
MARIANITO CV
MARIANITO CVMARIANITO CV
MARIANITO CV
 
Sondeo exploratorio
Sondeo exploratorioSondeo exploratorio
Sondeo exploratorio
 
Prospective clinical trial of traction device-assisted endoscopic submucosal ...
Prospective clinical trial of traction device-assisted endoscopic submucosal ...Prospective clinical trial of traction device-assisted endoscopic submucosal ...
Prospective clinical trial of traction device-assisted endoscopic submucosal ...
 
Connections
ConnectionsConnections
Connections
 
Try hard until you suceed (1)
Try hard until you suceed (1)Try hard until you suceed (1)
Try hard until you suceed (1)
 
How To Choose Perfect Hair Color ?
How To Choose Perfect Hair Color ?How To Choose Perfect Hair Color ?
How To Choose Perfect Hair Color ?
 
FEA - Simple Analysis example
FEA - Simple Analysis exampleFEA - Simple Analysis example
FEA - Simple Analysis example
 
Увеличение личных продаж от 3 раз и выше
Увеличение личных продаж от 3 раз и вышеУвеличение личных продаж от 3 раз и выше
Увеличение личных продаж от 3 раз и выше
 
Matthew Hartman cv.docx (1)
Matthew Hartman cv.docx (1)Matthew Hartman cv.docx (1)
Matthew Hartman cv.docx (1)
 
Steps to the college process
Steps to the college processSteps to the college process
Steps to the college process
 
Epoca precolombina tema 1
Epoca precolombina tema 1Epoca precolombina tema 1
Epoca precolombina tema 1
 
M025128139
M025128139M025128139
M025128139
 
Jerry Resume
Jerry ResumeJerry Resume
Jerry Resume
 
White Genocide In South Africa - Here Are The Names
White Genocide In South Africa - Here Are The NamesWhite Genocide In South Africa - Here Are The Names
White Genocide In South Africa - Here Are The Names
 

Similar to Test-Driven Development

Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Automation testing
Automation testingAutomation testing
Automation testingTomy Rhymond
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
Software Quality and Test Strategies for Ruby and Rails Applications
Software Quality and Test Strategies for Ruby and Rails ApplicationsSoftware Quality and Test Strategies for Ruby and Rails Applications
Software Quality and Test Strategies for Ruby and Rails ApplicationsBhavin Javia
 
Lightning Talks by Globant - Automation (This app runs by itself )
Lightning Talks by Globant -  Automation (This app runs by itself ) Lightning Talks by Globant -  Automation (This app runs by itself )
Lightning Talks by Globant - Automation (This app runs by itself ) Globant
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioAmit Choudhary
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 

Similar to Test-Driven Development (20)

TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Google test training
Google test trainingGoogle test training
Google test training
 
Software Quality and Test Strategies for Ruby and Rails Applications
Software Quality and Test Strategies for Ruby and Rails ApplicationsSoftware Quality and Test Strategies for Ruby and Rails Applications
Software Quality and Test Strategies for Ruby and Rails Applications
 
Lightning Talks by Globant - Automation (This app runs by itself )
Lightning Talks by Globant -  Automation (This app runs by itself ) Lightning Talks by Globant -  Automation (This app runs by itself )
Lightning Talks by Globant - Automation (This app runs by itself )
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Test driven development(tdd)
Test driven development(tdd)Test driven development(tdd)
Test driven development(tdd)
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 

More from John Blum

Getting Started with Apache Geode
Getting Started with Apache GeodeGetting Started with Apache Geode
Getting Started with Apache GeodeJohn Blum
 
Spring Data and In-Memory Data Management in Action
Spring Data and In-Memory Data Management in ActionSpring Data and In-Memory Data Management in Action
Spring Data and In-Memory Data Management in ActionJohn Blum
 
Spring Data (GemFire) Overview
Spring Data (GemFire) OverviewSpring Data (GemFire) Overview
Spring Data (GemFire) OverviewJohn Blum
 
Introducing Apache Geode and Spring Data GemFire
Introducing Apache Geode and Spring Data GemFireIntroducing Apache Geode and Spring Data GemFire
Introducing Apache Geode and Spring Data GemFireJohn Blum
 
Building Highly Scalable Spring Applications using In-Memory Data Grids
Building Highly Scalable Spring Applications using In-Memory Data GridsBuilding Highly Scalable Spring Applications using In-Memory Data Grids
Building Highly Scalable Spring Applications using In-Memory Data GridsJohn Blum
 
Building Effective Apache Geode Applications with Spring Data GemFire
Building Effective Apache Geode Applications with Spring Data GemFireBuilding Effective Apache Geode Applications with Spring Data GemFire
Building Effective Apache Geode Applications with Spring Data GemFireJohn Blum
 

More from John Blum (6)

Getting Started with Apache Geode
Getting Started with Apache GeodeGetting Started with Apache Geode
Getting Started with Apache Geode
 
Spring Data and In-Memory Data Management in Action
Spring Data and In-Memory Data Management in ActionSpring Data and In-Memory Data Management in Action
Spring Data and In-Memory Data Management in Action
 
Spring Data (GemFire) Overview
Spring Data (GemFire) OverviewSpring Data (GemFire) Overview
Spring Data (GemFire) Overview
 
Introducing Apache Geode and Spring Data GemFire
Introducing Apache Geode and Spring Data GemFireIntroducing Apache Geode and Spring Data GemFire
Introducing Apache Geode and Spring Data GemFire
 
Building Highly Scalable Spring Applications using In-Memory Data Grids
Building Highly Scalable Spring Applications using In-Memory Data GridsBuilding Highly Scalable Spring Applications using In-Memory Data Grids
Building Highly Scalable Spring Applications using In-Memory Data Grids
 
Building Effective Apache Geode Applications with Spring Data GemFire
Building Effective Apache Geode Applications with Spring Data GemFireBuilding Effective Apache Geode Applications with Spring Data GemFire
Building Effective Apache Geode Applications with Spring Data GemFire
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
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
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
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
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
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)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 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
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
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
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

Test-Driven Development

  • 2. AGENDA  Misconceptions  Why Test  Types of Tests  What & How to Test  Using JUnit, Mockito and MultithreadedTC  Best Practices  Final Thoughts  QA
  • 3. “No amount of testing can prove a software right, but a single test can prove a software wrong.” – Amir Ghahrai
  • 4. MISCONCEPTIONS Testing is a Quality Engineer’s (QE/SDET) job  Quality Assurance (QA) is everyone’s responsibility
  • 5. MISCONCEPTIONS Automated tests are unnecessary if I manually test and debug my code  Testing is not a replacement for debuggers and other development tools either (e.g. Profilers, FindBugs, etc) Not possible to automate all tests  Difficult when the software architecture & design is flawed
  • 6. Developer tests are “Unit Tests” JUnit is a “Unit Test” framework  JUnit is a framework facilitating the development and execution of automated tests  Used in Integration and Functional (Acceptance) testing MISCONCEPTIONS
  • 7. Software is correct when there is 100% test coverage and no FindBugs (CheckStyle, PMD) errors  A bug occurs when the software fails to function properly in a prescribed manner  A defect occurs after the software is used in a unintentional way and behaves unexpectedly MISCONCEPTIONS
  • 8. "Not everything that can be counted counts and not everything that counts can be counted." - Albert Einstein
  • 9. Why do software engineers write tests?
  • 10. Or… Why don’t software engineers write tests?
  • 11. TO TEST OR NOT TO TEST? Time Constraints  Time-based vs. Functional-based releases  Quantity (Scope) over Quality (Less is More) (Cultural) Responsibility Laziness, Ignorance, Fear  Not detail-oriented
  • 12. Verifies software is behaviorally correct and functionally complete  “Definition of Done” (DoD)  No “works on my box” arguments (we don’t ship your box) Ensures functional integration  Your code plays nicely with others Increases regression coverage  Tests in a suite is money in the bank; ensure what worked yesterday, works today and will work tomorrow WHY TEST
  • 14. WHY TEST Tests are a form of feedback  Developers get immediate feedback on changes to code by running the test(s) to ensure the “contract is upheld” Tests are a form of documentation  Demonstrates how the code (e.g. API) is properly used
  • 15. WHY TEST Focus on the problem that needs to be solved  Tests are a “contract for deliverables”; avoid “scope creep”  Tests limits “over-engineering” (future coders)  TDD Testing gives developers confidence in their changes  And more importantly… to “refactor” and make changes  To learn Testing encourages smaller, more frequent commits  And by extension, “releasable” code
  • 16. WHY TEST Testing identifies design flaws  Hard to test code is flawed and a sure sign of technical debt Untested code triggers a domino effect  User becomes the Tester leading to undesirable, costly “workarounds” leading to technical debt leading to other bugs leading to more serious issues like data corruption and so on
  • 17. “Don’t be that guy!” (the guy who doesn’t test his code)
  • 18. Why are there different types of tests?
  • 19. TYPES OF TESTS Different types of tests cover different “aspects” (concerns) of the software under test…  Different test types serve to “close the feedback loop” at different intervals in the software development lifecycle…
  • 20. TYPES OF TESTS Unit Tests  Tests a single, contained “unit” of functionality  Objects adhere to their contract (specified by the “interface”)  Class invariants are upheld as object state changes Integration Tests  Tests interactions between “collaborators”  Actual “dependencies” used
  • 21. TYPES OF TESTS Functional, Acceptance-based Tests (End-To-End)  Tests user/software interaction based on predefined workflows (Use Cases) and Functional Requirements  Acceptance Tests are defined by Acceptance Criteria (based on Functional Requirements)  Usability Testing (UAT) Performance-based Tests  load/stress testing
  • 23. “What” and “How” do you test?
  • 24. WHAT TO TEST Test everything (or as much as you can)!  Constructors, methods, input, output, Exception conditions, all code paths, invariants/object state, thread safety…  Test the unexpected Don’t make assumptions; verify with tests  “It is not only what you don’t know that gets you in trouble, it is what you thought you knew that just isn’t so!”
  • 25. ANATOMY OF A TEST Arrange Act Assert (Verify)
  • 26. How-To Unit Test Demonstration
  • 27. JUnit
  • 28. JUNIT - ASSERTIONS With assertThat(..)  More Readable (natural/DSL) and Strongly-typed  Assert subject (actual), verb, object (expected) Example assertThat(x is(3)); // assert “x is 3” or “x == 3” vs... assertEquals(3, x); // assert “equals 3 x” or “== 3 x” Examples…
  • 29. JUNIT - ASSUMPTIONS Useful to make test dependencies (pre-conditions) explicit  Examples: Environment Configuration, Resource Availability With assumeTrue(..) (JUnit) or the DSL-friendly assumeThat(..) (Hamcrest) Examples…
  • 30. JUNIT - EXCEPTIONS With Try/Catch Idiom (JUnit 3.x) With @Test(expected = Class<? extends Throwable>) With ExpectedException Rule (JUnit 4) Examples…
  • 31. JUNIT - PARAMETERIZED Parameterized test class instances created for the cross-product of test case methods and test data elements.  Useful for large volume of data Run test class with the Parameterized Test Runner. @RunWith(Parameterized.class) public class ParameterizedTest { @Parameters public Iterable<Object[]> data = …; public ParameterizedTest(..) { } } Example…
  • 32. JUNIT - RULES ErrorCollector – allows execution of test to continue after the first problem is encountered (Fail-Fast!) ExpectedException – specify expected error conditions in test ExternalResource – setup external resource (File, Socket, Database Connection, …) TemporaryFolder – creation of files and folders that are deleted after test case (method) finishes TestName – captures the name of a test inside test methods Timeout – applies same timeout to all test case methods in test class Example…
  • 33. JUNIT - TIMEOUTS With @Test(timeout = ms) @Test(timeout = 500) public void testWithTimeout() { } With Timeout Rule… public class TestsWithGlobalTimeout { @Rule public Timeout globalTimeout = Timeout.seconds(20); } Example…
  • 34. JUNIT – FIXTURES With @BeforeClass, @Before, @AfterClass, @After With (optionally) @ClassRule and ExternalResource Rule Examples…
  • 35. JUNIT – EXECUTION ORDER By design, JUnit does not specify test execution order  Test case method invocation determined by Reflection API  JDK 7 is more or less random Use MethodSorters and @FixMethodOrder annotation  E.g. @FixMethodOrder(MethodSorters.NAME_ASCENDING) Example…
  • 36. JUNIT – AGGREGATION Enables suites of tests to be grouped and built from existing test classes using… @RunWith(Suite.class) @Suite.SuiteClasses({ ClientCommandsTest.class, DiskStoreCommandsTest.class, FunctionCommandsTest.class, IndexCommandsTest.class, MemberCommandsTest.class, QueueCommandsTest.class, … }) public class GfshTestSuite { }
  • 37. JUNIT – ADDITIONAL FEATURES  Test Runners (e.g. Categories, Parameterized, MockitoJUnitRunner, SpringJUnit4ClassRunner)  Categories (e.g. UnitTests, IntegrationTests, AcceptanceTests)  Theories – more flexible/expressive assertions combined with ability to state assumptions  Rule Chaining – with RuleChain to control test rule ordering  Multithreaded Code and Concurrency (support)  Eh, MultithreadedTC is better!
  • 38. JUNIT – EXTENSIONS HttpUnit - http://httpunit.sourceforge.net/ HtmlUnit - http://htmlunit.sourceforge.net/ Selenium - http://www.seleniumhq.org/ JUext - http://junitext.sourceforge.net/ http://www.tutorialspoint.com/junit/junit_extensions.htm
  • 39. Unit Testing with Mocks using Mockito
  • 40. Why use Mocks in testing?
  • 41. UNIT TESTING WITH MOCKS Because… “If you can’t make it, fake it” Mocks ensure focus is on the Subject (“unit”) of the test by mocking interactions with Collaborators to verify appropriate behavior of the Subject, not the Collaborator(s)  Mocked Collaborators are “expected to behave” according to their contract Promotes programming to interfaces and delineation of functional responsibility across teams
  • 44. MOCKITO - CALLBACKS With… when(mock.doSomething(..)).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); Integer intArg = invocation.getArgumentAt(0, Integer.class); Object mock = invocation.getMock(); return …; } ));
  • 45. MOCKITO - STUBBING Consecutive calls… when(mock.getSomething(..)).thenReturn(“one”, “two”, “three”);
  • 46. MOCKITO – ORDER VERIFICATION With… InOrder inOrderVerifier = inOrder(firstMock, secondMock); inOrderVerifier.verify(firstMock, times(2)).doSomething(..); inOrderVerifier.verify(secondMock, atLeastOne()).doSomething(..);
  • 47. MOCKITO - SPIES Possible answer to… “Do not mock code you don’t own” List<Object> list = new ArrayList<Object>(); List<?> spy = spy(list); list.add(“one”); verify(spy, times(1)).add(eq(“one”));
  • 48. MOCKITO - LIMITATIONS Cannot mock final (non-extensible) classes or final (non- overridable) methods. Cannot stub Spies in the usual way… List<?> spy = spy(new ArrayList()); // Impossible – actual method is called so spy.get(0) throws IndexOutOfBoundsException when(spy.get(0).thenReturn(“TEST”); // Use doReturn(..) to do stubbing doReturn(“TEST”).when(spy).get(0); ??
  • 49. MOCKITO - EXTENSIONS PowerMock – enables mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers plus more…  Uses custom ClassLoader  https://code.google.com/p/powermock/
  • 51. BEST PRACTICES Test one thing at a time (per test case)  Single code path; one interaction with a collaborator; one user story, and so on…  Prefer more test cases rather than bloated test cases Tests should run quickly providing immediate feedback * 10-minute build Tests should fail-fast Tests should be 100% reliable
  • 52. BEST PRACTICES Please do not ignore (@Ignore) or comment out failing tests!  Understand test failures, take responsibility, fix the failures and don’t commit until all tests pass Write a test before fixing a bug  Without a test it is problematic to verify the fix
  • 53. BEST PRACTICES Test cases should be independent and execution order should not matter Use meaningful test case (method) names
  • 54. BEST PRACTICES Ideally, interchanging Mocks with actual Collaborators does not require any test changes
  • 55. BEST PRACTICES Follow the AAA Testing Pattern  Arrange -> Act -> Assert Follow the commit pattern… 1. Update, Create Topic Branch 2. Make Changes 3. Run Tests (if failure(s), goto 2) 4. Update (if changes, goto 3) 5. Merge & Commit
  • 56. FINAL TESTING THOUGHT Remember… There is “good code” and then there is “tested code”.