SlideShare a Scribd company logo
1 of 28
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

Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
Olga Extone
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
Mathieu Carbou
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 

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 introduction
Denis Bazhin
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 

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

Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
Muhammad Subhan
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Precisely
 

Recently uploaded (20)

Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.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