SlideShare a Scribd company logo
1 of 21
Introduction To JUnit
By Devvrat Shukla
Things to learn
“stepping stones”
1. Unit Testing
2. Test Phases
3. Test Fixture
4. Junit Introduction
5. Junit Features
6. Annotations
7. Assert Statements
8. Few Best Practice
Unit Testing

“helps you hunt down the bugs
before they mature”
• Unit testing is a software development process in
which the smallest testable parts of an
application, called units, are individually and
independently scrutinized for proper operation.
• Unit testing increases confidence in
changing/maintaining code.
• Every time any code is changed, the likelihood of
any defects due to the change being promptly
caught is very high.
• A unit test is a piece of code written by a
developer to test a unit. e.g. a method or a class,
(local tests).
• The percentage of code which is tested by unit
tests is typically called test coverage.
Test Phases

“four phases in the life of a unit test”
Set up

Exercise

Verify

Tear down

• Setting up the test fixture.

• Interact with the system under test.
• Determine whether the expected
outcome has been obtained
• Tear down the test fixture to return to
the original state.
Test Fixture

“setting the stage to perform unit
testing”
• In Software Testing, a test fixture is a fixed
state of the software under test used as a
baseline for running tests; also known as the
test context. It may also refer to the actions
performed in order to bring the system into
such a state.
• Examples of fixtures:
• Loading a database with a specific, known set of
data
• Erasing a hard disk and installing a known clean
operating system installation
• Copying a specific known set of files
• Preparation of input data and set-up/creation of
fake or mock objects
JUnit

“first testing then coding”
• Junit is a unit testing framework for the Java
Programming Language.
• JUnit is the Java version of the xUnit architecture for
unit- and regression-testing frameworks.
• Junit is a standard tool for test driven
development(TDD) in Java.
• Junit comes pre-bundled with several Java IDEs
(Eclipse, BlueJ, Jbuilder, etc).
• JUnit uses Java’s reflection capabilities (Java
programs can examine their own code)
• Beck and Gamma (of design patterns Gang of Four)
developed JUnit on a flight from Zurich to
Washington, D.C.
features

“yes, Its possible!”
• Provides Fixtures to set fixed state of the
software under test to be used as a baseline
for running tests
• Provides Annotation to identify the test
methods.
• Provides Assertions for testing expected
results.
• Provides TestRunner for running tests(main()).
• Provides TestSuite for organizing and running
groups of tests
• Junit shows test progress in a bar that is green
if test is going fine and it turns red when a test
fails.
@Annotations

“tell JUnit how to deal with the
method at hand”
Annotation
@Test
public void method()
@Test (expected = Exception.class)
@Test(timeout=100)
@Before
public void method()
@After
public void method()

Description
The @Test annotation identifies a method as a test method.
Fails, if the method does not throw the named exception.

Fails, if the method takes longer than 100 milliseconds.
This method is executed before each test. It is used to can prepare
the test environment (e.g. read input data, initialize the class).
This method is executed after each test. It is used to cleanup the
test environment (e.g. delete temporary data, restore defaults). It
can also save memory by cleaning up expensive memory structures.

@BeforeClass
public static void method()

This method is executed once, before the start of all tests. It is
used to perform time intensive activities, for example to connect
to a database. Methods annotated with this annotation need to be
defined as static to work with JUnit.

@AfterClass
public static void method()

This method is executed once, after all tests have been finished.
It is used to perform clean-up activities, for example to
disconnect from a database. Methods annotated with this annotation
need to be defined as static to work with JUnit.

@Ignore

Ignores the test method. This is useful when the underlying code
has been changed and the test case has not yet been adapted. Or if
the execution time of this test is too long to be included.
Note:
JUnit assumes that all test methods can be
executed in an arbitrary order. Therefore
tests should not depend on other tests.
Assert Statements

“compare the expected result with the
actual result”
• JUnit provides static methods in the Assert
class to test for certain conditions.
• These assertion methods typically start with
assert and allow you to specify the error
message, the expected and the actual result.
• Example:
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));
}

• An assertion method compares the actual
value returned by a test to the expected value,
and throws an AssertionException if the
comparison test fails.
Statement
Parameters in [] brackets are optional.

Description

fail(String)

Lets the method fail. Might be used to check that a
certain part of the code is not reached. Or to have a
failing test before the test code is implemented. The
String parameter is optional.

assertTrue([message], boolean condition)

Checks that the Boolean condition is true.

assertFalse([message], boolean condition)

Checks that the Boolean condition is false.

assertEquals([String message], expected,
actual)

Tests that two values are the same. Note: for arrays
the reference is checked not the content of the
arrays.

assertEquals([String message], expected,
actual, tolerance)

Test that float or double values match. The tolerance
is the number of decimals which must be the same.

assertNull([message], object)

Checks that the object is null.

assertNotNull([message], object)

Checks that the object is not null.

assertSame([String], expected, actual)

Checks that both variables refer to the same object.

assertNotSame([String], expected, actual)

Checks that both variables refer to different
objects.
Note:
You should provide meaningful messages in
assertions so that it is easier for the
developer to identify the problem. This helps
in fixing the issue, especially if someone
looks at the problem, which did not write the
code under test or the test code.
Happy Testing!

More Related Content

What's hot

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnitkleinron
 

What's hot (20)

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Google test training
Google test trainingGoogle test training
Google test training
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
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 best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Junit
JunitJunit
Junit
 

Viewers also liked

JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaRavikiran J
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 
JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondSam Brannen
 

Viewers also liked (8)

JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyond
 

Similar to Introduction to JUnit

Similar to Introduction to JUnit (20)

Junit
JunitJunit
Junit
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Junit
JunitJunit
Junit
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
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
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Test ng
Test ngTest ng
Test ng
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Unit testing
Unit testingUnit testing
Unit testing
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
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
Unit testingUnit testing
Unit testing
 
Unit testing using Munit Part 1
Unit testing using Munit Part 1Unit testing using Munit Part 1
Unit testing using Munit Part 1
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 

Introduction to JUnit

  • 1. Introduction To JUnit By Devvrat Shukla
  • 3. 1. Unit Testing 2. Test Phases 3. Test Fixture 4. Junit Introduction 5. Junit Features 6. Annotations 7. Assert Statements 8. Few Best Practice
  • 4. Unit Testing “helps you hunt down the bugs before they mature”
  • 5. • Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. • Unit testing increases confidence in changing/maintaining code. • Every time any code is changed, the likelihood of any defects due to the change being promptly caught is very high. • A unit test is a piece of code written by a developer to test a unit. e.g. a method or a class, (local tests). • The percentage of code which is tested by unit tests is typically called test coverage.
  • 6. Test Phases “four phases in the life of a unit test”
  • 7. Set up Exercise Verify Tear down • Setting up the test fixture. • Interact with the system under test. • Determine whether the expected outcome has been obtained • Tear down the test fixture to return to the original state.
  • 8. Test Fixture “setting the stage to perform unit testing”
  • 9. • In Software Testing, a test fixture is a fixed state of the software under test used as a baseline for running tests; also known as the test context. It may also refer to the actions performed in order to bring the system into such a state. • Examples of fixtures: • Loading a database with a specific, known set of data • Erasing a hard disk and installing a known clean operating system installation • Copying a specific known set of files • Preparation of input data and set-up/creation of fake or mock objects
  • 11. • Junit is a unit testing framework for the Java Programming Language. • JUnit is the Java version of the xUnit architecture for unit- and regression-testing frameworks. • Junit is a standard tool for test driven development(TDD) in Java. • Junit comes pre-bundled with several Java IDEs (Eclipse, BlueJ, Jbuilder, etc). • JUnit uses Java’s reflection capabilities (Java programs can examine their own code) • Beck and Gamma (of design patterns Gang of Four) developed JUnit on a flight from Zurich to Washington, D.C.
  • 13. • Provides Fixtures to set fixed state of the software under test to be used as a baseline for running tests • Provides Annotation to identify the test methods. • Provides Assertions for testing expected results. • Provides TestRunner for running tests(main()). • Provides TestSuite for organizing and running groups of tests • Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
  • 14. @Annotations “tell JUnit how to deal with the method at hand”
  • 15. Annotation @Test public void method() @Test (expected = Exception.class) @Test(timeout=100) @Before public void method() @After public void method() Description The @Test annotation identifies a method as a test method. Fails, if the method does not throw the named exception. Fails, if the method takes longer than 100 milliseconds. This method is executed before each test. It is used to can prepare the test environment (e.g. read input data, initialize the class). This method is executed after each test. It is used to cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures. @BeforeClass public static void method() This method is executed once, before the start of all tests. It is used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit. @AfterClass public static void method() This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit. @Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
  • 16. Note: JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.
  • 17. Assert Statements “compare the expected result with the actual result”
  • 18. • JUnit provides static methods in the Assert class to test for certain conditions. • These assertion methods typically start with assert and allow you to specify the error message, the expected and the actual result. • Example: @Test public void testMultiply() { MyClass tester = new MyClass(); assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5)); } • An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.
  • 19. Statement Parameters in [] brackets are optional. Description fail(String) Lets the method fail. Might be used to check that a certain part of the code is not reached. Or to have a failing test before the test code is implemented. The String parameter is optional. assertTrue([message], boolean condition) Checks that the Boolean condition is true. assertFalse([message], boolean condition) Checks that the Boolean condition is false. assertEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays. assertEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same. assertNull([message], object) Checks that the object is null. assertNotNull([message], object) Checks that the object is not null. assertSame([String], expected, actual) Checks that both variables refer to the same object. assertNotSame([String], expected, actual) Checks that both variables refer to different objects.
  • 20. Note: You should provide meaningful messages in assertions so that it is easier for the developer to identify the problem. This helps in fixing the issue, especially if someone looks at the problem, which did not write the code under test or the test code.

Editor's Notes

  1. JUnit promotes the idea of "first testing then coding", which emphasis on setting up the test data for a piece of code which can be tested first and then can be implemented. This approach is like "test a little, code a little, test a little, code a little..." which increases programmer productivity and stability of program code that reduces programmer stress and the time spent on debugging.