SlideShare a Scribd company logo
2/1/2021
Suraj Savaratkar
What is
Junit?
The JUnit Platform serves as a foundation for
launching testing frameworks on the JVM. It
also defines the TestEngine API for developing
a testing framework that runs on the
platform. Furthermore, the platform provides
a Console Launcher to launch the platform
from the command line and a JUnit 4 based
Runner for running any TestEngine on the
platform in a JUnit 4 based environment.
First-class support for the JUnit Platform also
exists in popular IDEs (see IntelliJ IDEA,
Eclipse, NetBeans, and Visual Studio Code)
and build tools (see Gradle, Maven, and Ant).
01-02-2021
Why Junit?
01-02-2021
Developer are write the code for business
functionality and the code will go on production. If
any mishap happens whole functionality will
collapse because of functional testing have not
write. To cover any sudden mishaps we should write
a Junit testing according to, what functionality have
implemented. The Junit framework make it
happens. Each Junit test case is independent and
can write multiple cases for each scenario. In
addition, tests are running concurrently. The
simplicity of Junit make it possible for the software
developer to easily correct bugs as they found. It
will also track the status of the code that was wrote
by somebody else and that tests are not affect by
newly added line. It also reduce the bugs in
delivered code.
• To isolate the each part of the application
• Show each isolated part is correct
2/1/2021
Junit History
01-02-2021
Basic Annotations
@BeforeClass – Run once before any of the test methods in the class, public static void
@AfterClass – Run once after all the tests in the class have been run, public static void
@Before – Run before @Test, public void
@After – Run after @Test, public void
@Test – This is the test method to run, public void
@Test (expected = Exception.class) – specify the what type exception should catch this test case, public void
@Ignore – This case is not execute it will ignored by TestEngine, public void
@RunWith - Tells JUnit to run using Spring’s testing support, Class level
@PrepareForTest - This annotation tells PowerMock to prepare certain classes for testing, Class level
@PrepareForTest(value = ClazzName.class) - This annotation tells PowerMock to prepare all tests from given
class for testing, Class level
01-02-2021
Basic Annotations (Cont.)
@Mock - Is used for mock creation. It makes the test class more readable.
@Spy - Is used to create a spy instance. We can use it instead spy(Object) method.
@InjectMocks - Is used to instantiate the tested object automatically and inject all the @Mock or
@Spy annotated field dependencies into it (if applicable).
@Captor - Is used to create an argument captor
01-02-2021
Few Basic Assert method
• assertArrayEquals (byte[] expecteds, byte[] actuals)
• assertArrayEquals(char[] expecteds, char[] actuals)
• assertEquals(long expected, long actual)
• assertEquals(java.lang.Object expected, java.lang.Object actual)
• assertFalse(boolean condition) assertFalse(java.lang.String message, boolean condition)
• fail(java.lang.String message)
• assertTrue(boolean condition)
• assertSame(java.lang.Object expected, java.lang.Object actual)
01-02-2021
Advantages
• Simple framework for writing automated, self-verifying tests in Java
• Support for test assertion
• Test suite development
• No state sharing
• Immediate test reporting
• Annotations to identify test methods
• It does not required to access the network
• It does not required to hit the database
• Does not use file system
01-02-2021
Advantages (Cont.)
• Reduce the number of bugs once deployed
01-02-2021
Lifecycle of the Test class
01-02-2021
Testing hierarchy
01-02-2021
Unit testing best practices
• 5 step
• Execution time – Be fast
• Consistent
• Atomic
• Single responsibility
• Test isolation
• Environment isolation
• Class isolation
• Fully automated
• Self-descriptive
• No conditional logic
• No loop
• No Exception catching
• Assertions
• Informative assertion messages
• No test logic in production code
• Separation per business modules
• Separation per type
01-02-2021
5 steps
• Setup
• Prepare an input
• Call a method
• Check output
• Tear down
01-02-2021
Execution time – Be fast
Frequent execution
• Several time per day – [Test After development]
• Several time per Hour –[Test driven development]
• Every few minutes – [IDE – Execution after save]
Execution in group
• 10 tests – execution time x 10
• 100 tests – execution time x 100
01-02-2021
Execution time – Be fast (Cont.)
What are good numbers?
Expected average execution time in junit testing:
• Single test – <200ms
• Small suite – <10s
• All test suites – <10 min
01-02-2021
Consistent
Multiple invocations of the test should consistently return true or false, provided no changes was
made on code.
How to deal with this?
• Mocks
• Dependency injection
01-02-2021
Automatic
• Only two possible results: true or false
• No partially success tests
• A test fails – The whole suite fails
01-02-2021
Single responsibilities
Test Behaviour, not methods:
• One method, multiple behaviours  Multiple tests
01-02-2021
Single responsibilities (Cont.)
• One behaviour, multiple methods  One Test
• A method calls private and protected methods
• A method calls very simple public methods
• (Specially, getters, setters, values objects simple constructor)
01-02-2021
Test isolation
Test should be independent from one another.
Different execution order - the same results
No state sharing
Instance variables:
• Junit - separated
• TestNG - shared
01-02-2021
Environment isolation
Unit test should be isolated from any environmental influence
• Database access
• Web services call
• JDNI lookup
• Environmental variables
• Property files
• System data and time
01-02-2021
Environment isolation (Cont.)
If class heavily uses the environment:
01-02-2021
Environment isolation (Cont.)
Under this unit testing is does not work:
01-02-2021
Environment isolation (Cont.)
The solution is mock:
01-02-2021
Environment isolation (Cont.)
Java mocking libraries:
• Easy mock
• Jmock
• Mockito
• Powermockito
01-02-2021
Classes isolation
01-02-2021
Classes isolation (Cont.)
Let see the example:
Steps 0: The class under test has no dependency
Step 1: The class is depends on some other
classes
01-02-2021
Classes isolation (Cont.)
Step 2: Dependencies of dependencies • Step 3: Dependencies of dependencies of
dependencies
01-02-2021
Classes isolation (Cont.)
• Step 4,5,6 Conclusion: Mocking the environment is not
enough
01-02-2021
Classes isolation (Cont.)
Solution: Mock the dependency Can be hard if code is not testable:
How to write testable code
• Do not call constructors inside a method.
Use factories of dependency injection
• Use interfaces
01-02-2021
Fully Automated
No manual steps involved into testing
• Automated tests execution
• Automated result gathering
• Automated decision making (success or failure)
• Automated result distribution
o Email
o System tray icon
o Dashboard web page
o IDE integration
01-02-2021
Self-descriptive
Unit test = development level documentation
Unit test = method specification which is always
up to date
Unit test must be easy to read and understand
• Variable names
• Method names Self-descriptive
• Class names
• No conditional logic
• No loops
01-02-2021
No conditional logic
Currently written test contains no “if” or
“switch” statements
No Uncertainty:
All inputs values should be known
Method behaviour should be predictable
Expected output should be strict
One test, multiple conditions
01-02-2021
No loops
Case 1: Hundreds of repetition
If some logic in a test has to be repeated hundreds of times, it probably means that the test is too
complicated and should be simplified.
Case 2: A few repetition
Repeating thing several times is OK, but it is better to type a code explicitly without loop. You can
extract the code which needs to be repeated into method and invoke it a few times in a row.
Case 3: Unknown number of repetitions
If you don’t know how many times you want to repeats the code and it makes you difficult to avoid
loops, it’s very likely that your test is incorrect rather focus on specifying more strict input data.
01-02-2021
No exception catching
Catch an exception only if its expected
Catch only expected type of an exception
Catch expected exception and call “fail”
method
Let other exceptions go uncatched
Catching expected exception
01-02-2021
Assertions
Use various types of assertions provided by a testing framework
Create your own assertions to check more complicated, repetitive conditions
Reuse your assertions methods
Loop inside assertions can be a good practice
01-02-2021
Informative assertion messages
By reading an assertion only, one should be able to recognize the problem.
It’s a good practice to include business logic information into messages
Assertion messages:
Improve documentation of the code
Inform about the problem in case of test failure
01-02-2021
No test logic in production code
Separate unit tests and production code
Don’t create methods/fields used only by unit tests
Use “dependency Injection”
01-02-2021
Separation per business module
Create suites of tests per business modules
Use hierarchical approach
Decrease the execution time of suites by splitting then into smaller ones (Per sub-module)
Small suites can be executed more frequently
01-02-2021
Separation per type
Keep unit tests separated from integration tests
Different purpose of execution
Different frequency of execution
Different time of execution
Different action in case of failure
01-02-2021
Write test case for controller layer
Annotate the class:
Import common static imports
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
01-02-2021
Write test case for controller layer (Cont.)
Mock the beans
Prepare the input:
Mock the method:
01-02-2021
Write test case for controller layer (Cont.)
Call a api:
TearDown
01-02-2021
Write test case
Annotated class
Mock the beans
01-02-2021
Write test case (Cont.)
Mock the methods
Call a method
Assertion
01-02-2021
Hierarchy of package structure
01-02-2021
Thanks

More Related Content

What's hot

Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
Sanjib Dhar
 
Test ng
Test ngTest ng
Test ng
fbenault
 
Junit
JunitJunit
TestNg_Overview_Config
TestNg_Overview_ConfigTestNg_Overview_Config
TestNg_Overview_Config
Abhishek Chakraborty
 
JUnit 5
JUnit 5JUnit 5
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
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributors
michael.labriola
 
Unit test
Unit testUnit test
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
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
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
Colombo Selenium Meetup
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKE
Abhishek Yadav
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Junit 4.0
Junit 4.0Junit 4.0
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
Gousalya Ramachandran
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
Denis Bazhin
 
J Unit
J UnitJ Unit
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
Animesh Kumar
 

What's hot (20)

Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
Test ng
Test ngTest ng
Test ng
 
Junit
JunitJunit
Junit
 
TestNg_Overview_Config
TestNg_Overview_ConfigTestNg_Overview_Config
TestNg_Overview_Config
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
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
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributors
 
Unit test
Unit testUnit test
Unit test
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
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
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKE
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
J Unit
J UnitJ Unit
J Unit
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 

Similar to TDD - Unit Testing

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
Hong Le Van
 
Software_testing.pptx
Software_testing.pptxSoftware_testing.pptx
Software_testing.pptx
556RajiniGali
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Anand Kumar Rajana
 
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
UTC Fire & Security
 
Unit testing
Unit testingUnit testing
Unit testing
Murugesan Nataraj
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
Facundo Farias
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
David P. Moore
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
Himanshu
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Testing 101
Testing 101Testing 101
Testing 101
Noam Barkai
 
Software Testing
Software TestingSoftware Testing
Software Testing
AdroitLogic
 
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoftEngineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
Jitendra Bafna
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptx
mianshafa
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
Macon Pegram
 

Similar to TDD - Unit Testing (20)

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Software_testing.pptx
Software_testing.pptxSoftware_testing.pptx
Software_testing.pptx
 
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 Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
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
 
Unit testing
Unit testingUnit testing
Unit testing
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Testing 101
Testing 101Testing 101
Testing 101
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoftEngineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
Engineering Student MuleSoft Meetup#4 - API Testing With MuleSoft
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptx
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 

Recently uploaded

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 

Recently uploaded (20)

GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 

TDD - Unit Testing

  • 2. What is Junit? The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and a JUnit 4 based Runner for running any TestEngine on the platform in a JUnit 4 based environment. First-class support for the JUnit Platform also exists in popular IDEs (see IntelliJ IDEA, Eclipse, NetBeans, and Visual Studio Code) and build tools (see Gradle, Maven, and Ant). 01-02-2021
  • 3. Why Junit? 01-02-2021 Developer are write the code for business functionality and the code will go on production. If any mishap happens whole functionality will collapse because of functional testing have not write. To cover any sudden mishaps we should write a Junit testing according to, what functionality have implemented. The Junit framework make it happens. Each Junit test case is independent and can write multiple cases for each scenario. In addition, tests are running concurrently. The simplicity of Junit make it possible for the software developer to easily correct bugs as they found. It will also track the status of the code that was wrote by somebody else and that tests are not affect by newly added line. It also reduce the bugs in delivered code. • To isolate the each part of the application • Show each isolated part is correct
  • 6. Basic Annotations @BeforeClass – Run once before any of the test methods in the class, public static void @AfterClass – Run once after all the tests in the class have been run, public static void @Before – Run before @Test, public void @After – Run after @Test, public void @Test – This is the test method to run, public void @Test (expected = Exception.class) – specify the what type exception should catch this test case, public void @Ignore – This case is not execute it will ignored by TestEngine, public void @RunWith - Tells JUnit to run using Spring’s testing support, Class level @PrepareForTest - This annotation tells PowerMock to prepare certain classes for testing, Class level @PrepareForTest(value = ClazzName.class) - This annotation tells PowerMock to prepare all tests from given class for testing, Class level 01-02-2021
  • 7. Basic Annotations (Cont.) @Mock - Is used for mock creation. It makes the test class more readable. @Spy - Is used to create a spy instance. We can use it instead spy(Object) method. @InjectMocks - Is used to instantiate the tested object automatically and inject all the @Mock or @Spy annotated field dependencies into it (if applicable). @Captor - Is used to create an argument captor 01-02-2021
  • 8. Few Basic Assert method • assertArrayEquals (byte[] expecteds, byte[] actuals) • assertArrayEquals(char[] expecteds, char[] actuals) • assertEquals(long expected, long actual) • assertEquals(java.lang.Object expected, java.lang.Object actual) • assertFalse(boolean condition) assertFalse(java.lang.String message, boolean condition) • fail(java.lang.String message) • assertTrue(boolean condition) • assertSame(java.lang.Object expected, java.lang.Object actual) 01-02-2021
  • 9. Advantages • Simple framework for writing automated, self-verifying tests in Java • Support for test assertion • Test suite development • No state sharing • Immediate test reporting • Annotations to identify test methods • It does not required to access the network • It does not required to hit the database • Does not use file system 01-02-2021
  • 10. Advantages (Cont.) • Reduce the number of bugs once deployed 01-02-2021
  • 11. Lifecycle of the Test class 01-02-2021
  • 13. Unit testing best practices • 5 step • Execution time – Be fast • Consistent • Atomic • Single responsibility • Test isolation • Environment isolation • Class isolation • Fully automated • Self-descriptive • No conditional logic • No loop • No Exception catching • Assertions • Informative assertion messages • No test logic in production code • Separation per business modules • Separation per type 01-02-2021
  • 14. 5 steps • Setup • Prepare an input • Call a method • Check output • Tear down 01-02-2021
  • 15. Execution time – Be fast Frequent execution • Several time per day – [Test After development] • Several time per Hour –[Test driven development] • Every few minutes – [IDE – Execution after save] Execution in group • 10 tests – execution time x 10 • 100 tests – execution time x 100 01-02-2021
  • 16. Execution time – Be fast (Cont.) What are good numbers? Expected average execution time in junit testing: • Single test – <200ms • Small suite – <10s • All test suites – <10 min 01-02-2021
  • 17. Consistent Multiple invocations of the test should consistently return true or false, provided no changes was made on code. How to deal with this? • Mocks • Dependency injection 01-02-2021
  • 18. Automatic • Only two possible results: true or false • No partially success tests • A test fails – The whole suite fails 01-02-2021
  • 19. Single responsibilities Test Behaviour, not methods: • One method, multiple behaviours  Multiple tests 01-02-2021
  • 20. Single responsibilities (Cont.) • One behaviour, multiple methods  One Test • A method calls private and protected methods • A method calls very simple public methods • (Specially, getters, setters, values objects simple constructor) 01-02-2021
  • 21. Test isolation Test should be independent from one another. Different execution order - the same results No state sharing Instance variables: • Junit - separated • TestNG - shared 01-02-2021
  • 22. Environment isolation Unit test should be isolated from any environmental influence • Database access • Web services call • JDNI lookup • Environmental variables • Property files • System data and time 01-02-2021
  • 23. Environment isolation (Cont.) If class heavily uses the environment: 01-02-2021
  • 24. Environment isolation (Cont.) Under this unit testing is does not work: 01-02-2021
  • 25. Environment isolation (Cont.) The solution is mock: 01-02-2021
  • 26. Environment isolation (Cont.) Java mocking libraries: • Easy mock • Jmock • Mockito • Powermockito 01-02-2021
  • 28. Classes isolation (Cont.) Let see the example: Steps 0: The class under test has no dependency Step 1: The class is depends on some other classes 01-02-2021
  • 29. Classes isolation (Cont.) Step 2: Dependencies of dependencies • Step 3: Dependencies of dependencies of dependencies 01-02-2021
  • 30. Classes isolation (Cont.) • Step 4,5,6 Conclusion: Mocking the environment is not enough 01-02-2021
  • 31. Classes isolation (Cont.) Solution: Mock the dependency Can be hard if code is not testable: How to write testable code • Do not call constructors inside a method. Use factories of dependency injection • Use interfaces 01-02-2021
  • 32. Fully Automated No manual steps involved into testing • Automated tests execution • Automated result gathering • Automated decision making (success or failure) • Automated result distribution o Email o System tray icon o Dashboard web page o IDE integration 01-02-2021
  • 33. Self-descriptive Unit test = development level documentation Unit test = method specification which is always up to date Unit test must be easy to read and understand • Variable names • Method names Self-descriptive • Class names • No conditional logic • No loops 01-02-2021
  • 34. No conditional logic Currently written test contains no “if” or “switch” statements No Uncertainty: All inputs values should be known Method behaviour should be predictable Expected output should be strict One test, multiple conditions 01-02-2021
  • 35. No loops Case 1: Hundreds of repetition If some logic in a test has to be repeated hundreds of times, it probably means that the test is too complicated and should be simplified. Case 2: A few repetition Repeating thing several times is OK, but it is better to type a code explicitly without loop. You can extract the code which needs to be repeated into method and invoke it a few times in a row. Case 3: Unknown number of repetitions If you don’t know how many times you want to repeats the code and it makes you difficult to avoid loops, it’s very likely that your test is incorrect rather focus on specifying more strict input data. 01-02-2021
  • 36. No exception catching Catch an exception only if its expected Catch only expected type of an exception Catch expected exception and call “fail” method Let other exceptions go uncatched Catching expected exception 01-02-2021
  • 37. Assertions Use various types of assertions provided by a testing framework Create your own assertions to check more complicated, repetitive conditions Reuse your assertions methods Loop inside assertions can be a good practice 01-02-2021
  • 38. Informative assertion messages By reading an assertion only, one should be able to recognize the problem. It’s a good practice to include business logic information into messages Assertion messages: Improve documentation of the code Inform about the problem in case of test failure 01-02-2021
  • 39. No test logic in production code Separate unit tests and production code Don’t create methods/fields used only by unit tests Use “dependency Injection” 01-02-2021
  • 40. Separation per business module Create suites of tests per business modules Use hierarchical approach Decrease the execution time of suites by splitting then into smaller ones (Per sub-module) Small suites can be executed more frequently 01-02-2021
  • 41. Separation per type Keep unit tests separated from integration tests Different purpose of execution Different frequency of execution Different time of execution Different action in case of failure 01-02-2021
  • 42. Write test case for controller layer Annotate the class: Import common static imports import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 01-02-2021
  • 43. Write test case for controller layer (Cont.) Mock the beans Prepare the input: Mock the method: 01-02-2021
  • 44. Write test case for controller layer (Cont.) Call a api: TearDown 01-02-2021
  • 45. Write test case Annotated class Mock the beans 01-02-2021
  • 46. Write test case (Cont.) Mock the methods Call a method Assertion 01-02-2021
  • 47. Hierarchy of package structure 01-02-2021