SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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 FrameworkOnkar Deshpande
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
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
 
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.1Kiki Ahmadi
 
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 practicesNarendra 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? | EdurekaEdureka!
 

La actualidad más candente (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 a Testing with Junit4

Similar a 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
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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

Notas del editor

  1. public static Test suite() {} FileTest