SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Kürzlich hochgeladen (20)

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

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.