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

PPTX
PDF
TestNG - The Next Generation of Unit Testing
PPT
PPTX
Introduction to JUnit
PDF
Unit testing with Junit
PDF
TestNG vs. JUnit4
PPTX
TestNG vs Junit
PPTX
Testing with Junit4
TestNG - The Next Generation of Unit Testing
Introduction to JUnit
Unit testing with Junit
TestNG vs. JUnit4
TestNG vs Junit
Testing with Junit4

What's hot (20)

PPT
05 junit
PPTX
PPTX
Java Unit Test - JUnit
PPTX
TestNG Data Binding
PPTX
TestNG Framework
PPTX
Test ng tutorial
PPSX
PPT
Junit and testNG
PPTX
Unit Testing with JUnit4 by Ravikiran Janardhana
PDF
Unit testing with JUnit
PPTX
JUnit- A Unit Testing Framework
PDF
JUnit Pioneer
PDF
JUnit & Mockito, first steps
PPTX
TestNG Session presented in PB
PPS
JUnit Presentation
PDF
PPTX
TestNG vs JUnit: cease fire or the end of the war
PPTX
Test NG Framework Complete Walk Through
PPT
JUnit 4
05 junit
Java Unit Test - JUnit
TestNG Data Binding
TestNG Framework
Test ng tutorial
Junit and testNG
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit testing with JUnit
JUnit- A Unit Testing Framework
JUnit Pioneer
JUnit & Mockito, first steps
TestNG Session presented in PB
JUnit Presentation
TestNG vs JUnit: cease fire or the end of the war
Test NG Framework Complete Walk Through
JUnit 4
Ad

Similar to Junit (20)

PPTX
Unit Testing in Java
PDF
junit-160729073220 eclipse software testing.pdf
PDF
TestNG introduction
PPTX
Unit Testng with PHP Unit - A Step by Step Training
PPTX
unit 1 (1).pptx
PPTX
Software Testing and JUnit and Best Practices
PPTX
Introduction to JUnit testing in OpenDaylight
PPTX
Python: Object-Oriented Testing (Unit Testing)
PPTX
Cpp unit
PPTX
Session 4 -Junit- Testing Exceptions, Junit hooks.pptx
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
PDF
Effective Unit Test Style Guide
PPTX
.Net Unit Testing with Visual Studio 2010
PPTX
Presentation android JUnit
PPTX
Unit testing using Munit Part 1
PPTX
Unit testing
PPTX
Unit testing
PPTX
Unit tests and TDD
PPTX
8-testing.pptx
Unit Testing in Java
junit-160729073220 eclipse software testing.pdf
TestNG introduction
Unit Testng with PHP Unit - A Step by Step Training
unit 1 (1).pptx
Software Testing and JUnit and Best Practices
Introduction to JUnit testing in OpenDaylight
Python: Object-Oriented Testing (Unit Testing)
Cpp unit
Session 4 -Junit- Testing Exceptions, Junit hooks.pptx
2.Python_Testing_Using_PyUnit_PyTest.pptx
Effective Unit Test Style Guide
.Net Unit Testing with Visual Studio 2010
Presentation android JUnit
Unit testing using Munit Part 1
Unit testing
Unit testing
Unit tests and TDD
8-testing.pptx
Ad

Recently uploaded (20)

PPTX
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
PPTX
GSA Content Generator Crack (2025 Latest)
PDF
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
DOCX
How to Use SharePoint as an ISO-Compliant Document Management System
PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PPTX
Trending Python Topics for Data Visualization in 2025
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
Autodesk AutoCAD Crack Free Download 2025
PPTX
Cybersecurity: Protecting the Digital World
PPTX
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
PPTX
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
iTop VPN Crack Latest Version Full Key 2025
PPTX
Tech Workshop Escape Room Tech Workshop
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
GSA Content Generator Crack (2025 Latest)
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
How to Use SharePoint as an ISO-Compliant Document Management System
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
CCleaner 6.39.11548 Crack 2025 License Key
Trending Python Topics for Data Visualization in 2025
Salesforce Agentforce AI Implementation.pdf
Autodesk AutoCAD Crack Free Download 2025
Cybersecurity: Protecting the Digital World
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
Advanced SystemCare Ultimate Crack + Portable (2025)
iTop VPN Crack Latest Version Full Key 2025
Tech Workshop Escape Room Tech Workshop

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.