SlideShare a Scribd company logo
An Introduction To
Unit Testing & TDD
Content
1. Introduction
2. Unit Tests
3. Mocking
4. TDD
Introduction
Introduction
› Software development without testing.
› Not every part of the program should be
tested.
› Testing leads to higher software quality.
Testing Levels/Types
1. Acceptance Tests
2. System Tests
3. Integration Tests
4. Unit Tests
Acceptance
System
Unit
Integration
High Level
Low Level
Evaluate the
system's
compliance with
the business
requirements
After the system
testing is over, the
software is tested
by the client/user.
Acceptance Testing
Testing an
integrated system
to verify that it
meets specified
requirements.
Done by software
testing team.
Used to verify the
functionality,
performance, and
reliability of the
modules that are
integrated.
Either performed by
developers or testing
team, this depends on
the integrated layer
under test
The main aim is to
isolate each unit of
the system to
identify, analyze
and fix the defects.
Only a developer
should do it.
System Testing Integration Testing Unit Testing
Unit Tests
Unit Testing
› Aims to test the functionality of an isolated unit.
› Greatly helps in refactoring.
› Testing a function across two classes is
integration testing, not unit testing.
› Java has two major unit testing frameworks:
JUnit & TestNG.
› Code coverage: how many tests are executed
when running unit tests. Its frameworks are
JaCoCo, EclEMMA ( or EMMA)
Why Unit Testing?
› Quick changes to the
code.
› Documents code
design.
› Instant visual feedback
and diagnosis.
› Predict bugs and lower
development time.
› Verify code correctness.
Unit Testing Frameworks
JUnit
› Latest is JUnit5
› Most used test
framework, the official
Java test framework
TestNG
› Latest is TestNG 6
› Less used framework
but still favored by
many developers
1. TestNG had more features than JUnit4 but with JUnit 5 they
became almost equal to each other.
2. TestNG a little better reporting and support for parallelism
3. Maven supports using test units for both of them.
4. I will use JUnit in my example because it has more public
support but TestNG is an excellent framework nonetheless.
Simple JUnit Test Example
MyUnit.java
public class MyUnit {
public String
concatenate(String one,
String two){
return one + two;
}
}
MyTests.java
import org.junit.Test;
import static org.junit.Assert.*;
public class MyUnitTest {
@Test
public void testConcatenate() {
MyUnit myUnit = new MyUnit();
String result = myUnit.concatenate("one",
"two");
assertEquals("onetwo", result);
}
}
Basic JUnit Features & Annotations
@Test(expected, timeout): used to annotate a test.
@Before: annotates a function that runs before every test.
@BeforeClass: runs once before the whole class finishes execution.
@After: runs after every test.
@AfterClass: runs once after the whole class finishes execution.
@Ignore: a test function that is disabled.
Assert.*: multiple functions that are used to assert the correctness
of a test result (assertEquals, assertFalse, assertArraysEqual , ...etc.).
Test suite: it is a way to group test classes and run them together.
@Suite.SuiteClasses({tests .class array}): test classes of the suite.
@RunWith(Class<Runner>): marks the runner class which is a class
that implements Runner and used to run test classes with special
requirements( ex: PowerMockRunner.class & Suite.class )
Mocking
Mocking
› As we need to isolate a unit for testing,
the need for mocking has arisen.
› Before mocking, people had to create
fake classes to simulate the dependency.
› It is creating dependencies that simulate
the behavior of real dependencies.
› It also can verify function call.
› Mostly used for unit tests layer.
How Mocking Works
A proxy is made using reflection for
interfaces and bytecode rewrites for
mocking concrete classes.
As for mocking a static class, the classloader
is modified in compile-time to use a special
proxy class instead of the original class.
Java Mocking Frameworks
1. Mockito: Simple & clean API.Easy to learn.
2. PowerMock: Used for special cases, solves
Mockito disadvantages.
3. JMockit: Can mock every dependency but has a
steep learning curve.
4. EasyMock: Has many flexible options for
mocking, but has a small community.
I will be using Mockito + PowerMock combination
in my example as that give allow powerful
mocking that’s easy to learn.
Mockito Annotations & Features
@Mock/mock(): tells Mockito to mock objects, every function
will return an object or null/primitive type if not specified
@InjectMock: tells Mockito to inject its mocks into an object.
Mockito.verify(someFunction(),times(#)): verifies number of
calls of a specific function.
Mockito.when(someFunction()).[thenReturn()|thenAnswer()|the
nThrow()|thenCallRealMethod()]: stubs an action when a
mocked function is used.
Mockito.[doNothing()|doReturn()|doThrow()|doAnswer()].when
(mockObject).someFunction(): mocks a void function behaviour.
@Spy/Mockito.spy(new someObject): allows partial mocking so
only mocked functions return results but non-mocked functions
will work normally.
@Captor/Mockito.ArgumentCaptor: a special class to capture
the argument passed to a function when verifying it.
Mockito Example
@RunWith(MockitoJUnitRunner.class)
public class ItemServiceTest {
@Mock private ItemRepository itemRepository;
@InjectMocks private ItemService itemService;
@Test
public void getItemNameUpperCase() {
Item mockedItem = new Item("it1", "Item 1", "This is item 1", 2000, true);
when(itemRepository.findById("it1")).thenReturn(mockedItem);
String result = itemService.getItemNameUpperCase("it1");
verify(itemRepository, times(1)).findById("it1");
assertThat(result, "ITEM 1");
}
}
PowerMock
› It solves Mockito shortcomings.
› Used to mock constructors, static, final
and private methods.
› Mostly delegates the actual mocking to
the underlying mocking framework as
Mockito or EasyMock.
PowerMockito
› PowerMockito class is the integration
between Mockito and PowerMock.
› PowerMockito has most of Mockito
methods like mock(),spy(),when(),
doNothing() or thenReturn().
› It also has some other methods such as
mockStatic(), verifyStatic()
Mockito + PowerMock Example
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticService.class})
public class ItemServiceTest {
@Mock
private ItemRepository itemRepository;
@InjectMocks
private ItemService itemService;
@Before
public void setUp() throws Exception {MockitoAnnotations.initMocks(this);}
@Test
public void readItemDescriptionWithoutIOException() throws IOException {
String fileName = "DummyName";
PowerMockito.mockStatic(StaticService.class);
when(StaticService.readFile(fileName)).thenReturn("Dummy");
String value = itemService.readItemDescription(fileName);
PowerMockito.verifyStatic(times(1));
StaticService.readFile(fileName);
assertThat(value, "Dummy");
}
}
Test-Driven
Development (TDD)
Background
Test-Driven Development (TDD) originated
from eXtreme Programming (XP) paradigm
but continued into modern Agile paradigms.
A software development technique where
developers write a failing test that will
define the functionality before writing
actual code.
TDD Cycle and Rules
Red RefactorGreen
1. First, write an initially failing (RED) automated test case
that defines a new functionality.
2. Then produces the minimum amount of code to pass
(GREEN) test.
3. Finally refactors (REFACTOR) the new code to
acceptable standards.
4. Run tests again after refactoring if it fails re-do the cycle.
The cycles should be as short as possible.
TDD Flowchart
Add a test
Run The Test
Run the tests
Make a little change
[Pass]
[Fail]
[Fail]
[Pass]
Refactor
[Pass Refactoring]
[Development
Ends]
[Development
Continues]
› Ensures a clean working code that fulfills
requirements.
› Greatly decrease defects in the long run
with a slight increase in initial
development time.
› Increases productivity in the long run.
› Leads to high code coverage and more
unit tests as developers only write code
with preliminary tests.
Why TDD?
TDD Case Studies
Microsoft
40%-90%
pre-release defect
density decrease
with an increase of
15%-35% in initial
development.
IBM
40% fewer defects
with almost no
impact on team’s
productivity.
Ericsson
TDD increased
software quality
with an increase of
15% of initial
development.
Thanks!!

More Related Content

What's hot

Junit
JunitJunit
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unitOlga Extone
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
Narendra Pathai
 
TestNG
TestNGTestNG
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
Sanjib Dhar
 
J Unit
J UnitJ Unit
Test ng
Test ngTest ng
Test ng
fbenault
 
Introduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkIntroduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit framework
BugRaptors
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
Andrey Oleynik
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
David Noble
 
Software testing basics and its types
Software testing basics and its typesSoftware testing basics and its types
Software testing basics and its types
360logica Software Testing Services (A Saksoft Company)
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 

What's hot (20)

Junit
JunitJunit
Junit
 
TestNg_Overview_Config
TestNg_Overview_ConfigTestNg_Overview_Config
TestNg_Overview_Config
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
TestNG
TestNGTestNG
TestNG
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
J Unit
J UnitJ Unit
J Unit
 
Test ng
Test ngTest ng
Test ng
 
Introduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkIntroduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit framework
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Software testing basics and its types
Software testing basics and its typesSoftware testing basics and its types
Software testing basics and its types
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Unit test
Unit testUnit test
Unit test
 
Mockito
MockitoMockito
Mockito
 

Similar to An Introduction To Unit Testing and TDD

Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
JMockit
JMockitJMockit
JMockit
Angad Rajput
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
OpenDaylight
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
alessiopace
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
Mario Peshev
 
Introduction to Testing Frameworks
Introduction to Testing Frameworks Introduction to Testing Frameworks
Introduction to Testing Frameworks
Hemant Shori
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
romanovfedor
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
ssuserd0fdaa
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Flutter Agency
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
Himanshu
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
IT Event
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 

Similar to An Introduction To Unit Testing and TDD (20)

Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
JMockit
JMockitJMockit
JMockit
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Introduction to Testing Frameworks
Introduction to Testing Frameworks Introduction to Testing Frameworks
Introduction to Testing Frameworks
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 

Recently uploaded

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
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
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
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
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
 
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
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
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
 

Recently uploaded (20)

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
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
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
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
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...
 
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
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
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
 

An Introduction To Unit Testing and TDD

  • 1. An Introduction To Unit Testing & TDD
  • 2. Content 1. Introduction 2. Unit Tests 3. Mocking 4. TDD
  • 4. Introduction › Software development without testing. › Not every part of the program should be tested. › Testing leads to higher software quality.
  • 5. Testing Levels/Types 1. Acceptance Tests 2. System Tests 3. Integration Tests 4. Unit Tests Acceptance System Unit Integration High Level Low Level
  • 6. Evaluate the system's compliance with the business requirements After the system testing is over, the software is tested by the client/user. Acceptance Testing Testing an integrated system to verify that it meets specified requirements. Done by software testing team. Used to verify the functionality, performance, and reliability of the modules that are integrated. Either performed by developers or testing team, this depends on the integrated layer under test The main aim is to isolate each unit of the system to identify, analyze and fix the defects. Only a developer should do it. System Testing Integration Testing Unit Testing
  • 8. Unit Testing › Aims to test the functionality of an isolated unit. › Greatly helps in refactoring. › Testing a function across two classes is integration testing, not unit testing. › Java has two major unit testing frameworks: JUnit & TestNG. › Code coverage: how many tests are executed when running unit tests. Its frameworks are JaCoCo, EclEMMA ( or EMMA)
  • 9. Why Unit Testing? › Quick changes to the code. › Documents code design. › Instant visual feedback and diagnosis. › Predict bugs and lower development time. › Verify code correctness.
  • 10. Unit Testing Frameworks JUnit › Latest is JUnit5 › Most used test framework, the official Java test framework TestNG › Latest is TestNG 6 › Less used framework but still favored by many developers 1. TestNG had more features than JUnit4 but with JUnit 5 they became almost equal to each other. 2. TestNG a little better reporting and support for parallelism 3. Maven supports using test units for both of them. 4. I will use JUnit in my example because it has more public support but TestNG is an excellent framework nonetheless.
  • 11. Simple JUnit Test Example MyUnit.java public class MyUnit { public String concatenate(String one, String two){ return one + two; } } MyTests.java import org.junit.Test; import static org.junit.Assert.*; public class MyUnitTest { @Test public void testConcatenate() { MyUnit myUnit = new MyUnit(); String result = myUnit.concatenate("one", "two"); assertEquals("onetwo", result); } }
  • 12. Basic JUnit Features & Annotations @Test(expected, timeout): used to annotate a test. @Before: annotates a function that runs before every test. @BeforeClass: runs once before the whole class finishes execution. @After: runs after every test. @AfterClass: runs once after the whole class finishes execution. @Ignore: a test function that is disabled. Assert.*: multiple functions that are used to assert the correctness of a test result (assertEquals, assertFalse, assertArraysEqual , ...etc.). Test suite: it is a way to group test classes and run them together. @Suite.SuiteClasses({tests .class array}): test classes of the suite. @RunWith(Class<Runner>): marks the runner class which is a class that implements Runner and used to run test classes with special requirements( ex: PowerMockRunner.class & Suite.class )
  • 14. Mocking › As we need to isolate a unit for testing, the need for mocking has arisen. › Before mocking, people had to create fake classes to simulate the dependency. › It is creating dependencies that simulate the behavior of real dependencies. › It also can verify function call. › Mostly used for unit tests layer.
  • 15. How Mocking Works A proxy is made using reflection for interfaces and bytecode rewrites for mocking concrete classes. As for mocking a static class, the classloader is modified in compile-time to use a special proxy class instead of the original class.
  • 16. Java Mocking Frameworks 1. Mockito: Simple & clean API.Easy to learn. 2. PowerMock: Used for special cases, solves Mockito disadvantages. 3. JMockit: Can mock every dependency but has a steep learning curve. 4. EasyMock: Has many flexible options for mocking, but has a small community. I will be using Mockito + PowerMock combination in my example as that give allow powerful mocking that’s easy to learn.
  • 17. Mockito Annotations & Features @Mock/mock(): tells Mockito to mock objects, every function will return an object or null/primitive type if not specified @InjectMock: tells Mockito to inject its mocks into an object. Mockito.verify(someFunction(),times(#)): verifies number of calls of a specific function. Mockito.when(someFunction()).[thenReturn()|thenAnswer()|the nThrow()|thenCallRealMethod()]: stubs an action when a mocked function is used. Mockito.[doNothing()|doReturn()|doThrow()|doAnswer()].when (mockObject).someFunction(): mocks a void function behaviour. @Spy/Mockito.spy(new someObject): allows partial mocking so only mocked functions return results but non-mocked functions will work normally. @Captor/Mockito.ArgumentCaptor: a special class to capture the argument passed to a function when verifying it.
  • 18. Mockito Example @RunWith(MockitoJUnitRunner.class) public class ItemServiceTest { @Mock private ItemRepository itemRepository; @InjectMocks private ItemService itemService; @Test public void getItemNameUpperCase() { Item mockedItem = new Item("it1", "Item 1", "This is item 1", 2000, true); when(itemRepository.findById("it1")).thenReturn(mockedItem); String result = itemService.getItemNameUpperCase("it1"); verify(itemRepository, times(1)).findById("it1"); assertThat(result, "ITEM 1"); } }
  • 19. PowerMock › It solves Mockito shortcomings. › Used to mock constructors, static, final and private methods. › Mostly delegates the actual mocking to the underlying mocking framework as Mockito or EasyMock.
  • 20. PowerMockito › PowerMockito class is the integration between Mockito and PowerMock. › PowerMockito has most of Mockito methods like mock(),spy(),when(), doNothing() or thenReturn(). › It also has some other methods such as mockStatic(), verifyStatic()
  • 21. Mockito + PowerMock Example @RunWith(PowerMockRunner.class) @PrepareForTest({StaticService.class}) public class ItemServiceTest { @Mock private ItemRepository itemRepository; @InjectMocks private ItemService itemService; @Before public void setUp() throws Exception {MockitoAnnotations.initMocks(this);} @Test public void readItemDescriptionWithoutIOException() throws IOException { String fileName = "DummyName"; PowerMockito.mockStatic(StaticService.class); when(StaticService.readFile(fileName)).thenReturn("Dummy"); String value = itemService.readItemDescription(fileName); PowerMockito.verifyStatic(times(1)); StaticService.readFile(fileName); assertThat(value, "Dummy"); } }
  • 23. Background Test-Driven Development (TDD) originated from eXtreme Programming (XP) paradigm but continued into modern Agile paradigms. A software development technique where developers write a failing test that will define the functionality before writing actual code.
  • 24. TDD Cycle and Rules Red RefactorGreen 1. First, write an initially failing (RED) automated test case that defines a new functionality. 2. Then produces the minimum amount of code to pass (GREEN) test. 3. Finally refactors (REFACTOR) the new code to acceptable standards. 4. Run tests again after refactoring if it fails re-do the cycle. The cycles should be as short as possible.
  • 25. TDD Flowchart Add a test Run The Test Run the tests Make a little change [Pass] [Fail] [Fail] [Pass] Refactor [Pass Refactoring] [Development Ends] [Development Continues]
  • 26. › Ensures a clean working code that fulfills requirements. › Greatly decrease defects in the long run with a slight increase in initial development time. › Increases productivity in the long run. › Leads to high code coverage and more unit tests as developers only write code with preliminary tests. Why TDD?
  • 27.
  • 28.
  • 29. TDD Case Studies Microsoft 40%-90% pre-release defect density decrease with an increase of 15%-35% in initial development. IBM 40% fewer defects with almost no impact on team’s productivity. Ericsson TDD increased software quality with an increase of 15% of initial development.