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

05 junit
05 junit05 junit
05 junit
mha4
 
Junit 4.0
Junit 4.0Junit 4.0
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
Aktuğ Urun
 
TestNG Data Binding
TestNG Data BindingTestNG Data Binding
TestNG Data Binding
Matthias Rothe
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 
Junit
JunitJunit
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
Ravikiran J
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Pokpitch Patcharadamrongkul
 
TestNG
TestNGTestNG
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
Scott Leberknight
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
Abhishek Yadav
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
JUnit 5
JUnit 5JUnit 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
Oleksiy Rezchykov
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 

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

Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Junit
JunitJunit
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
Denis 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 Training
Ram Awadh Prasad, PMP
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
SumitKumar918321
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
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)
Damian T. Gordon
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
mudabbirwarsi
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
Jacky 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 2010
kgayda
 
Presentation android JUnit
Presentation android JUnitPresentation android JUnit
Presentation android JUnit
Enrique López Mañas
 
Unit testing using Munit Part 1
Unit testing using Munit Part 1Unit testing using Munit Part 1
Unit testing using Munit Part 1
Anand kalla
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Unit testing
Unit testingUnit testing
Unit testing
princezzlove
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
ssuserd0fdaa
 
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
PyCon Italia
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
Unit testing
Unit testingUnit testing
Unit testing
Vinod Wilson
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 

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

Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 

Recently uploaded (20)

Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 

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.