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

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
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
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
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
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Último (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
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
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 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
 
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
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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