SlideShare a Scribd company logo
1 of 19
JUNIT
JAVA TESTING UNIT
1
Content
• Unit tests and unit testing
• Unit testing with JUnit
• Available JUnit annotations
• Assertions
• Test Suites
• Rules
• Mocking libraries
• EasyMock
• Code coverage libraries
• Cobertura
Unit tests and unit testing
• a unit test is a piece of code written by a developer that executes a
specific functionality in the code to be tested.
• a unit test targets a small unit of code, e.g., a method or a class
• it ensures that code works as intended, (code still works as
intended in case you need to modify code for fixing a bug or
extending functionality).
Unit tests and unit testing
• the percentage of code which is tested by unit tests is typically
called test coverage.
• having a high test coverage of your code allows you to
continue developing features without having to perform lots
of manual tests.
Unit testing with JUNIT
• JUnit (http://junit.org/) is a test framework which uses
annotations to identify methods that specify a test. Typically
these test methods are contained in a class which is only used
for testing. It is typically called a Test class.
• current stable version: 4.11
Unit testing with JUNIT
Example:
package bogcon.dbintruder.tests.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import bogcon.dbintruder.core.Parameters;
/**
* ParametersTest class.<br />
* Test cases for {@link Parameters} class.
*
* @author Bogdan Constantinescu <bog_con@yahoo.com>
*/
public class ParametersTest {
@Test
public void testGeneralOperations() {
Parameters p = new Parameters();
p.add("param1", "param1Value");
assertEquals(p.getCount(), 1);
assertTrue(p.get("param1").contains("param1Value"));
}
}
Unit testing with JUNIT
- to run the test:
java -cp .:/path/to/junit.jar org.junit.runner.JUnitCore [test class name]
- all tests methods are annotated with @Test, no need too
prefix methods name with test as in JUnit3
- no need to extend anything (junit.framework.TestCase as in
JUnit3)
Available JUnit annotations
Annotation Description
@Test
public void method()
The @Test annotation identifies a method as a test
method.
@Test (expected =
Exception.class)
Fails if the method does not throw the named
exception.
@Test(timeout=100) Fails if the method takes longer than 100 milliseconds.
@Before
public void method()
This method is executed before each test. It is used to
prepare the test environment (e.g., read input data,
initialize the class).
@After
public void method()
This method is executed after each test. It is used to
cleanup the test environment (e.g., delete temporary
data, restore defaults). It can also save memory by
cleaning up expensive memory structures.
Available JUnit annotations
Annotation Description
@BeforeClass
public static void
method()
This method is executed once, before the start of all tests. It is
used to perform time intensive activities, for example, to
connect to a database. Methods marked with this annotation
need to be defined as static to work with JUnit.
@AfterClass
public static void
method()
This method is executed once, after all tests have been
finished. It is used to perform clean-up activities, for example,
to disconnect from a database. Methods annotated with this
annotation need to be defined as static to work with JUnit.
@Ignore Ignores the test method. This is useful when the underlying
code has been changed and the test case has not yet been
adapted. Or if the execution time of this test is too long to be
included.
Assertions
Statement Description
fail(String) Let the method fail. Might be used to check that a certain
part of the code is not reached or to have a failing test
before the test code is implemented. The String
parameter is optional.
assertTrue([message],
boolean condition)
Checks that the boolean condition is true.
assertFalse([message],
boolean condition)
Checks that the boolean condition is false.
assertEquals([String
message], expected,
actual)
Tests that two values are the same. Note: for arrays the
reference is checked not the content of the arrays.
assertEquals([String
message], expected,
actual, tolerance)
Test that float or double values match. The tolerance is
the number of decimals which must be the same.
Assertions
Statement Description
assertNull([message], object) Checks that the object is null.
assertNotNull([message],
object)
Checks that the object is not null.
assertSame([String],
expected, actual)
Checks that both variables refer to the same object.
assertNotSame([String],
expected, actual)
Checks that both variables refer to different objects.
assertArrayEquals([String],
expected, actual)
Checks both array contains same values
Test Suites
• combine multiple tests into a test suite
• a test suite executes all test classes in that
suite in the specified order
• Example:
package bogcon.dbintruder.tests.core;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ ParametersTest.class, SqlErrorsTest.class, UtilsTest.class,
WebTechnologyTest.class, HttpClientTest.class, AnalyzerTest.class,
OsETest.class })
public class AllNonLiveTests {
}
Rules
Example how to specify which exception message you expect during
execution of your test code:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class RuleExceptionTesterExample {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void throwsIllegalArgumentExceptionIfIconIsNull() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Negative value not allowed"); ClassToBeTested t =
new ClassToBeTested(); t.methodToBeTest(-1);
}
}
Rules
Example how setup files & folders which are automatically removed after
a test:
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class RuleTester {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File createdFolder = folder.newFolder("newfolder");
File createdFile = folder.newFile("myfilefile.txt");
assertTrue(createdFile.exists());
}
}
Mocking libraries
• Jmockit https://code.google.com/p/jmockit/
• EasyMock
http://easymock.org/
• Mockito
https://code.google.com/p/mockito/
• PowerMock
https://code.google.com/p/powermock/
EasyMock
• is a mock framework which can be easily used in conjunction with Junit
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createMockBuilder;
...
HttpClient mock = createMockBuilder(HttpClient.class)
.addMockedMethod("get")
.addMockedMethod("getLastResponse")
.createMock();
HttpClient mockHC = createMock(HttpClient.class);
expect(mockHC.get(url)).andReturn(this.response1).once();
expect(mockHC.get(url)).andThrow(new DBIntruderException("")).times(2);
expect(mockHC.get(matches(Pattern.quote("http://www.agenda.dev/index.php?id=") + "[0-9a-zA-
Z_-]+" + Pattern.quote("&param=blabla"))))
.andReturn(this.response2).once();
Code coverage libraries
• Clover
https://www.atlassian.com/software/clover/overview
• EMMA
http://emma.sourceforge.net/index.html
• Cobertura
http://cobertura.github.io/cobertura/
Cobertura
• Cobertura is a free Java tool that calculates the percentage of
code accessed by tests. It can be used to identify which parts
of your Java program are lacking test coverage.
THANK YOU!
Bogdan Constantinescu
INNOBYTE

More Related Content

What's hot (20)

05 junit
05 junit05 junit
05 junit
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
TestNG Data Binding
TestNG Data BindingTestNG Data Binding
TestNG Data Binding
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Junit
JunitJunit
Junit
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
TestNG
TestNGTestNG
TestNG
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 

Similar to Junit

TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
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 TrainingRam Awadh Prasad, PMP
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightOpenDaylight
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Damian T. Gordon
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010kgayda
 
Unit testing using Munit Part 1
Unit testing using Munit Part 1Unit testing using Munit Part 1
Unit testing using Munit Part 1Anand kalla
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest modulePyCon Italia
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 

Similar to Junit (20)

Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Junit
JunitJunit
Junit
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
Presentation android JUnit
Presentation android JUnitPresentation android JUnit
Presentation android JUnit
 
Unit testing using Munit Part 1
Unit testing using Munit Part 1Unit testing using Munit Part 1
Unit testing using Munit Part 1
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Unit testing
Unit testingUnit testing
Unit testing
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

Junit

  • 2. Content • Unit tests and unit testing • Unit testing with JUnit • Available JUnit annotations • Assertions • Test Suites • Rules • Mocking libraries • EasyMock • Code coverage libraries • Cobertura
  • 3. Unit tests and unit testing • a unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested. • a unit test targets a small unit of code, e.g., a method or a class • it ensures that code works as intended, (code still works as intended in case you need to modify code for fixing a bug or extending functionality).
  • 4. Unit tests and unit testing • the percentage of code which is tested by unit tests is typically called test coverage. • having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.
  • 5. Unit testing with JUNIT • JUnit (http://junit.org/) is a test framework which uses annotations to identify methods that specify a test. Typically these test methods are contained in a class which is only used for testing. It is typically called a Test class. • current stable version: 4.11
  • 6. Unit testing with JUNIT Example: package bogcon.dbintruder.tests.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import bogcon.dbintruder.core.Parameters; /** * ParametersTest class.<br /> * Test cases for {@link Parameters} class. * * @author Bogdan Constantinescu <bog_con@yahoo.com> */ public class ParametersTest { @Test public void testGeneralOperations() { Parameters p = new Parameters(); p.add("param1", "param1Value"); assertEquals(p.getCount(), 1); assertTrue(p.get("param1").contains("param1Value")); } }
  • 7. Unit testing with JUNIT - to run the test: java -cp .:/path/to/junit.jar org.junit.runner.JUnitCore [test class name] - all tests methods are annotated with @Test, no need too prefix methods name with test as in JUnit3 - no need to extend anything (junit.framework.TestCase as in JUnit3)
  • 8. Available JUnit annotations Annotation Description @Test public void method() The @Test annotation identifies a method as a test method. @Test (expected = Exception.class) Fails if the method does not throw the named exception. @Test(timeout=100) Fails if the method takes longer than 100 milliseconds. @Before public void method() This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class). @After public void method() This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
  • 9. Available JUnit annotations Annotation Description @BeforeClass public static void method() This method is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit. @AfterClass public static void method() This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit. @Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
  • 10. Assertions Statement Description fail(String) Let the method fail. Might be used to check that a certain part of the code is not reached or to have a failing test before the test code is implemented. The String parameter is optional. assertTrue([message], boolean condition) Checks that the boolean condition is true. assertFalse([message], boolean condition) Checks that the boolean condition is false. assertEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays. assertEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
  • 11. Assertions Statement Description assertNull([message], object) Checks that the object is null. assertNotNull([message], object) Checks that the object is not null. assertSame([String], expected, actual) Checks that both variables refer to the same object. assertNotSame([String], expected, actual) Checks that both variables refer to different objects. assertArrayEquals([String], expected, actual) Checks both array contains same values
  • 12. Test Suites • combine multiple tests into a test suite • a test suite executes all test classes in that suite in the specified order • Example: package bogcon.dbintruder.tests.core; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ParametersTest.class, SqlErrorsTest.class, UtilsTest.class, WebTechnologyTest.class, HttpClientTest.class, AnalyzerTest.class, OsETest.class }) public class AllNonLiveTests { }
  • 13. Rules Example how to specify which exception message you expect during execution of your test code: import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class RuleExceptionTesterExample { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void throwsIllegalArgumentExceptionIfIconIsNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Negative value not allowed"); ClassToBeTested t = new ClassToBeTested(); t.methodToBeTest(-1); } }
  • 14. Rules Example how setup files & folders which are automatically removed after a test: import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class RuleTester { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testUsingTempFolder() throws IOException { File createdFolder = folder.newFolder("newfolder"); File createdFile = folder.newFile("myfilefile.txt"); assertTrue(createdFile.exists()); } }
  • 15. Mocking libraries • Jmockit https://code.google.com/p/jmockit/ • EasyMock http://easymock.org/ • Mockito https://code.google.com/p/mockito/ • PowerMock https://code.google.com/p/powermock/
  • 16. EasyMock • is a mock framework which can be easily used in conjunction with Junit import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.createMockBuilder; ... HttpClient mock = createMockBuilder(HttpClient.class) .addMockedMethod("get") .addMockedMethod("getLastResponse") .createMock(); HttpClient mockHC = createMock(HttpClient.class); expect(mockHC.get(url)).andReturn(this.response1).once(); expect(mockHC.get(url)).andThrow(new DBIntruderException("")).times(2); expect(mockHC.get(matches(Pattern.quote("http://www.agenda.dev/index.php?id=") + "[0-9a-zA- Z_-]+" + Pattern.quote("&param=blabla")))) .andReturn(this.response2).once();
  • 17. Code coverage libraries • Clover https://www.atlassian.com/software/clover/overview • EMMA http://emma.sourceforge.net/index.html • Cobertura http://cobertura.github.io/cobertura/
  • 18. Cobertura • Cobertura is a free Java tool that calculates the percentage of code accessed by tests. It can be used to identify which parts of your Java program are lacking test coverage.