SlideShare a Scribd company logo
1
What is JUnit ?
• JUnit is a Regression Testing Framework* for
the Java Programming Language.
• One of a family of unit testing frameworks
collectively known as xUnit.
• Open source framework
*One of the main reasons for regression testing is to
determine whether a change in one part of the
software affects other parts of the software
Features
• Provides Annotation to identify the test
methods.
• Provides Assertions for testing expected results.
• Provides Test runners for running tests.
Coding Conventions
o Name of the test class end with "Test".
o Name of the method begin with "test".
o Return type of a test method must be void.
o Test method must not throw any exception.
o Test method must not have any parameter.
4
Simple Test
public class FooTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
// Tests
assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
}
}
Component of JUnit
• JUnit test framework provides following
important features/component
oFixtures
oAssertions (provides Assert API)
oTest suites (TestSuite API)
oJUnit classes
Fixtures
• Fixtures is a fixed state of a set of objects used as a
baseline for running tests. The purpose of a test fixture is
to ensure that there is a well known and fixed
environment in which tests are run so that results are
repeatable.
- Usage -
o Preparation of input data and setup/creation of fake or
mock objects
o Loading a database with a specific, known set of data
o Copying a specific known set of files creating a test
fixture will create a set of objects initialized to certain
states.
7
8
Assert
public class Assert extends java.lang.Object
• This class provides a set of assertion methods useful for
writing tests. Only failed assertions are recorded.
• JUnit provides overloaded assertion methods for all
primitive types and Objects and arrays (of primitives or
Objects)
• If fail AssertionFailedError
Assert Methods
Test Suite
• Test suite means bundle a few unit test cases
and run it together. In JUnit,
both @RunWith and @Suite annotation are
used to run the suite test.
11
TestSuite Example
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestFeatureLogin.class,
TestFeatureLogout.class,
TestFeatureNavigate.class,
TestFeatureUpdate.class
})
public class FeatureTestSuite {
// the class remains empty,
// used only as a holder for the above annotations
}
Test execution order
• JUnit does not specify the execution order of test method
invocations
• From version 4.11, JUnit will by default use a deterministic,
but not predictable, order (MethodSorters.DEFAULT)
• @FixMethodOrder(MethoSorters.JVM): Leaves the test
methods in the order returned by the JVM. This order may
vary from run to run.
• @FixMethodOrder(MethodSorters.NAME_ASCENDING):
Sorts the test methods by method name, in lexicographic
order.
Some More Features
Ignore Test
• Sometimes it happens that our code is not ready
and test case written to test that method/code
will fail if run or we just don’t want to test that
test case at that moment.
The @Ignore annotation helps in this regards.
oA test method annotated with @Ignore will not
be executed.
oIf a test class is annotated with @Ignore then all
of its test methods will be ignored.
Ignored Test Example
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IgnoreTest {
@Test
public void notIgnored()
{
System.out.println("this is executed");
}
@Ignore
@Test
public void itIsIgnored()
{
System.out.println("This test is ignored");
}
}
Time test
• Junit provides a handy option of Timeout. If a
test case takes more time than specified number
of milliseconds then Junit will automatically
mark it as failed. The timeout parameter is
used along with @Test annotation.
Time Test xample
import org.junit.Test;
public class TimeTest {
@Test(timeout=10)
public void testTime()
{
for(int i=0;i<1000;i++){
System.out.println("hiiiiii");
}
}
}
Exception Test
• Junit provides a option of tracing the Exception
handling of code. You can test the code whether
code throws desired exception or not.
The expected parameter is used along with
@Test annotation.
Exception Test Example
import org.junit.Test;
public class ExceptionTest {
@Test(expected=ArithmeticException.class)
public void exception() {
int s=12/0;
}
}
Parameterized Test
• Junit 4 has introduced a new feature Parameterized
tests.Parameterized tests allow developer to run the
same test over and over again using different values.
There are five steps, that you need to follow to
create Parameterized tests.
o Annotate test class with @RunWith(Parameterized.class)
o Create a public static method annotated with @Parameters that
returns a Collection of Objects (as Array) as test data set.
o Create a public constructor that takes in what is equivalent to one
"row" of test data.
o Create an instance variable for each "column" of test data.
o Create your tests case(s) using the instance variables as the source
of the test data.
Parameterized Test Example
executed three times
Rules
• Via the @Rule annotation you can create objects
which can be used and configured in your test
methods.
• This adds more flexibility to your tests.
• Testers can reuse or extend one of the provided
Rules ,or write their own.
Rule sample
More Rules
TemporaryFolder The TemporaryFolder Rule allows creation of files
and folders that are guaranteed to be deleted when
the test method finishes (whether it passes or fails):
Timeout The Timeout Rule applies the same timeout to all test
methods in a class
TestName The TestName Rule makes the current test name
available inside test methods
ErrorCollector The ErrorCollector rule allows execution of a test to
continue after the first problem is found (for example,
to collect _all_ the incorrect rows in a table, and
report them all at once):
ExpectedException The ExpectedException Rule allows in-test
specification of expected exception types and
messages:
Categories
• From a given set of test classes, the Categories
runner runs only the classes and methods that
are annotated with either the category given with
the @IncludeCategory annotation, or a subtype
of that category
References
• http://www.vogella.com/tutorials/JUnit/article.
html
• http://junit.org/
• http://www.slideshare.net/killisss/junit4testng-
presentation?related=1

More Related Content

What's hot

Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Pokpitch Patcharadamrongkul
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unitOlga Extone
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
Valerio Maggio
 
J Unit
J UnitJ Unit
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
Ted Vinke
 
Junit
JunitJunit
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
Kiki Ahmadi
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
Scott Leberknight
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Thomas Zimmermann
 
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
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
Edureka!
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
Junit
JunitJunit

What's hot (20)

Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Junit
JunitJunit
Junit
 
J Unit
J UnitJ Unit
J Unit
 
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
 
Junit
JunitJunit
Junit
 
3 j unit
3 j unit3 j unit
3 j unit
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
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
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Junit
JunitJunit
Junit
 

Similar to Testing with Junit4

TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
Abhishek Yadav
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
OpenDaylight
 
testng
testngtestng
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
ssuserd0fdaa
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
Sanjib Dhar
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
SumitKumar918321
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
Sunil kumar Mohanty
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
mudabbirwarsi
 
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
Ram Awadh Prasad, PMP
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdet
devlabsalliance
 

Similar to Testing with Junit4 (20)

Junit
JunitJunit
Junit
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
Test ng
Test ngTest ng
Test ng
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
testng
testngtestng
testng
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit
JUnitJUnit
JUnit
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
 
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
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdet
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
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
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
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
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
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
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
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...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.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
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
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
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 

Testing with Junit4

  • 1. 1
  • 2. What is JUnit ? • JUnit is a Regression Testing Framework* for the Java Programming Language. • One of a family of unit testing frameworks collectively known as xUnit. • Open source framework *One of the main reasons for regression testing is to determine whether a change in one part of the software affects other parts of the software
  • 3. Features • Provides Annotation to identify the test methods. • Provides Assertions for testing expected results. • Provides Test runners for running tests.
  • 4. Coding Conventions o Name of the test class end with "Test". o Name of the method begin with "test". o Return type of a test method must be void. o Test method must not throw any exception. o Test method must not have any parameter. 4
  • 5. Simple Test public class FooTest { @Test public void testMultiply() { MyClass tester = new MyClass(); // Tests assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0)); assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10)); assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0)); } }
  • 6. Component of JUnit • JUnit test framework provides following important features/component oFixtures oAssertions (provides Assert API) oTest suites (TestSuite API) oJUnit classes
  • 7. Fixtures • Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. - Usage - o Preparation of input data and setup/creation of fake or mock objects o Loading a database with a specific, known set of data o Copying a specific known set of files creating a test fixture will create a set of objects initialized to certain states. 7
  • 8. 8
  • 9. Assert public class Assert extends java.lang.Object • This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. • JUnit provides overloaded assertion methods for all primitive types and Objects and arrays (of primitives or Objects) • If fail AssertionFailedError
  • 11. Test Suite • Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. 11
  • 12. TestSuite Example import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestFeatureLogin.class, TestFeatureLogout.class, TestFeatureNavigate.class, TestFeatureUpdate.class }) public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations }
  • 13. Test execution order • JUnit does not specify the execution order of test method invocations • From version 4.11, JUnit will by default use a deterministic, but not predictable, order (MethodSorters.DEFAULT) • @FixMethodOrder(MethoSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run. • @FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.
  • 15. Ignore Test • Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run or we just don’t want to test that test case at that moment. The @Ignore annotation helps in this regards. oA test method annotated with @Ignore will not be executed. oIf a test class is annotated with @Ignore then all of its test methods will be ignored.
  • 16. Ignored Test Example import org.junit.Ignore; import org.junit.Test; @Ignore public class IgnoreTest { @Test public void notIgnored() { System.out.println("this is executed"); } @Ignore @Test public void itIsIgnored() { System.out.println("This test is ignored"); } }
  • 17. Time test • Junit provides a handy option of Timeout. If a test case takes more time than specified number of milliseconds then Junit will automatically mark it as failed. The timeout parameter is used along with @Test annotation.
  • 18. Time Test xample import org.junit.Test; public class TimeTest { @Test(timeout=10) public void testTime() { for(int i=0;i<1000;i++){ System.out.println("hiiiiii"); } } }
  • 19. Exception Test • Junit provides a option of tracing the Exception handling of code. You can test the code whether code throws desired exception or not. The expected parameter is used along with @Test annotation.
  • 20. Exception Test Example import org.junit.Test; public class ExceptionTest { @Test(expected=ArithmeticException.class) public void exception() { int s=12/0; } }
  • 21. Parameterized Test • Junit 4 has introduced a new feature Parameterized tests.Parameterized tests allow developer to run the same test over and over again using different values. There are five steps, that you need to follow to create Parameterized tests. o Annotate test class with @RunWith(Parameterized.class) o Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. o Create a public constructor that takes in what is equivalent to one "row" of test data. o Create an instance variable for each "column" of test data. o Create your tests case(s) using the instance variables as the source of the test data.
  • 23. Rules • Via the @Rule annotation you can create objects which can be used and configured in your test methods. • This adds more flexibility to your tests. • Testers can reuse or extend one of the provided Rules ,or write their own.
  • 25. More Rules TemporaryFolder The TemporaryFolder Rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails): Timeout The Timeout Rule applies the same timeout to all test methods in a class TestName The TestName Rule makes the current test name available inside test methods ErrorCollector The ErrorCollector rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once): ExpectedException The ExpectedException Rule allows in-test specification of expected exception types and messages:
  • 26. Categories • From a given set of test classes, the Categories runner runs only the classes and methods that are annotated with either the category given with the @IncludeCategory annotation, or a subtype of that category
  • 27.
  • 28. References • http://www.vogella.com/tutorials/JUnit/article. html • http://junit.org/ • http://www.slideshare.net/killisss/junit4testng- presentation?related=1

Editor's Notes

  1. public static Test suite() {} FileTest