You are on page 1of 22

JUNIT

Java unit test, by Martin Nad


martin_m_nad@yahoo.com
Junit

OVERVIEW

This documentation is about how you can test


your java application and what you have to
think about, and why you should test

Page 2
Junit

TABLE OF CONTEXT:

FORWORD

WHITE BOX TESTING

BLACK BOX TESTGING

DEFINITION OF TESTING

UNIT TEST

ROLLS

JUNIT

ADVENTAGES WITH JUNIT

PRINCIPLES OF TEST

HOW JUNIT IS WORKING

DIFFERENT KIND OF JUNIT TESTING

TEST METHODE

HOW TO USE THE TEST RUNNER

OTHER DIFFERNT KIND OF JUNIT

LIST OF DIFFERENT KIND OF SOFTWARE TESTING

MY OTHER DOCUMENTATION

Page 3
Junit

Page 4
Junit

Junit
FORWORD

One of the most important phases of software developing is


testing.
We have different kind of testing, but we can group all of them
in to two categories:
1. Black box testing,
2 .white box testing
Unit testing is a kind of “white-box-testing”

WHITE BOX TESTING

White box testing is about internal design and structure test


and I’m goanna to discuss about it.

BLACK BOX TESTING

Black box testing is about functional and none-functional


testing.

Page 5
Junit

The functional testing is about input and behaviour and


output testing
None-functional testing is about reliability test , scalability and
software performance.
The aim of this documentation is: how we can test our
application with focusing to internally structure and JUNIT.

DEFINITION OF TESTING

It is not very simple to define what it is a testing a bout,


because we have too many different kind of testing as:
We can have validating testing and verification testing,
We can have usability testing and security-testing and so on,
there are more than 20 different kind of testing. We can
define testing just whit respect to what we want to test.
I can very easily define as follow: Software testing helps us to
find any error/bug in an application before we deliver or put it
on the live-environment. The errors can be validation,
verfication, security and so on.

Page 6
Junit

UNIT TEST

ROLLS
When you want to write your Test-class you should think about
that
-just have one assert per test
-just test one functionallity per test

JUNIT

Junit is a framework to write tests case and during the


developing, debugging, adding features we can reuse the
same test and we can add new test case of course. Junit is
about internally-test or some kind of white box-testing and it
can help us to find error in early stage and during developing,
debugging or refactoring.

We should test our application before and after we implement


any new featuer to the application.

ADVENTAGES WITH JUNIT

Page 7
Junit

Junit is a kind of white box testing, and it is just about internal


structure testing.
You can find error in very early staging and during your
developing phase.
It helps you to locate and find very precisely place of error
and even find error and during debugging and refactoring

PRINCIPLES OF TEST

We should have a test case for every variation type of input,


also not every possible instance of input.

We should test cases for combinations or permutation of all


variation types of the implemented operations.
For example, if we have a string-compare function
We should test just with two different strings to check the
string-compare function with two different options
1- If the string1 is equal with string2
2- If the string1 is part of string2

It is important to know how the test should happen for


example for a multiplication-operation, it is enough to test just

Page 8
Junit

one positive number and 0, and you shouldn’t test all positive
number to each other.
And if you want to test the border on your operation you can
just test with two big integer numbers together.

HOW JUNIT IS WORKING

What you have to test, can be:


requiredResult= achivedResult
Or in other form:
requiredResult.equals(achivedResult) ;

You should to know that it is not necessary to use junit for


testing your structure, you can just write your own test-
program and just use it.

Example 1

Page 9
Junit

• if (achivedResult == null || !
requiredResult.equals(achivedResult) ) throw new
MyTestyException(“Unexcepted Result");
• With JUnit, you can code import static org.junit.Assert.*; ...
assertEquals(“Unexcepted Result", expectedResults,
requiredResults);
• Every part of junit asserts method throws by
java.lang.AssertionErrors if the test fails.

DIFFERENT KIND OF JUNIT TESTING

• You can find lot of various assert depend on your test, here
is just a short list of the whole assert-methods:
• assertArrayEquals
• AssertEquals
• assertFalse
• assertNotNull
• assertNotSame
• assertNull
• assertThat

Page 10
Junit

• assertTrue
• Fails

You will find the whole definition of methods on

TEST METHODE

• For example if you have n-numbers of the methods, it is


better you have a test-case for each of methods. Junit should
test all and report if all of test passed throw or which one was
failed. • Something that interesting it can one of the method,
or test, cause very violet result, and in this case you can find
it easily
• @org.junit.Test
public void testGetPropertyWithReplacements() {
PropertyManager propManager = new PropertyManager();
propManager.init();
String replacedString =
propManager.getPropertyWithReplacements ("text.to.replace",
replacements);
assertTrue(replacedString.indexOf(replacem ents[0]) > 0);
}

Page 11
Junit

• You should have some init method without any parameters.


You can call it whatever, but it shouldn’t have any parameters.
• You should to remember that any test unit or methods
should be single threaded and it shouldn’t depend to any
other test-unit or values of static variables or instance.
• And if you want to use any instance of variables, each test-
methods should
Handling throwables in test methods

@org.junit.Test
public void testGetPropertyWithReplacements() {
Try{
PropertyManager propManager = new PropertyManager();
propManager.init(); String replacedString =
propManager.getPropertyWithReplacements("text.to.replace",
replacements);
assertTrue(replacedString.indexOf(replacements[0]) > 0); }
catch(Exception e){ AssertionError ae = new AssertionError(
“test Application failed to confirm the properties");
ae.initCause(e); throw ae;
}}

DIFFERENCES BETWEEN JUNIT FAILURES AND ERRORS

Page 12
Junit

• A failure is a test-process that your code has failed by using


a certain process for the aim of the method • And a error, is
get unexpected problem

EXAMPLE 3

Import java.lang.*;
Public class StringTest extend AbstractStringTest{
@Test Void testString(){...}
@Test Void testString1(){...}
@Before Void testEqual(){...}
@Before Void testEqual_1(){...}
@After Void testContians(){}
@After Void testContians1(){} }

• The anotation @befor and @after specify the methods order


to execute
• The order of this test is:
• testEqual()
• testEqual_1()
• ........
• testString()
• testString1()

Page 13
Junit

• .........
• Testcontains()
• TestContains1()
• But the order in the those three groups can changes
• As I saild before the test-methods should be independent to
each other.

HOW TO USE THE TEST RUNNER

• From command line you can very easily use this command •
Java –cp path_to_thte libjunit.jar org.junit.runner.JUnitCore
com.acme.LoadTester yourpackege.yourclass
• From main:
• public static void main(
String args[]) {
org.junit.runner.JUnitCore.main(You rTester.class.getName());
}

HOW USE JUNIT WITH ANT

Page 14
Junit

• And this an example of ant-script to running Junit-test


<project default="all">
<property name="tst-dir" location="test" />
<property name="TEST" value="true" />
<path id="classpath.base">
</path>
<path id="classpath.test">
<pathelement location="/Projects/Java/Lib/junit.jar" />
<pathelement location="${tst-dir}" />
<path refid="classpath.base" />
</path>
<target name="compile-test">
<javac srcdir="${tst-dir}" verbose="${TEST}" >
<classpath refid="classpath.test"/>
</javac>
</target>
<target name="clean-compile-test">
<delete verbose="${TEST}">
<fileset dir="${tst-dir}" includes="**/*.class" />
</delete>
</target>
<target name="test" depends="compile-test">

Page 15
Junit

<junit>
<classpath refid="classpath.test" />
<formatter type="brief" usefile="false" />
<test name="TestExample" />
</junit>
</target>

OTHER DIFFERNT KIND OF UNIT TEST

• Easy moch: http://easymock.org/


• Power moch: http://code.google.com/p/powermock/
• Mockito: http://code.google.com/p/mockito/
• Jmock: http://jmock.org/
• Fest mocks http://fest.easytesting.org/mocks/wiki/pm

LIST OF DIFFERENT KIND OF SOFTWARE TESTING

Black box testing - Internal system design is not considered in this type of testing. Tests
are based on requirements and functionality.

White box testing - This testing is based on knowledge of the internal logic of an
application’s code. Also known as Glass box Testing. Internal software and code working

Page 16
Junit

should be known for this type of testing. Tests are based on coverage of code statements,
branches, paths, conditions.

Unit testing - Testing of individual software components or modules. Typically done by


the programmer and not by testers, as it requires detailed knowledge of the internal
program design and code. may require developing test driver modules or test harnesses.

Incremental integration testing - Bottom up approach for testing i.e continuous testing
of an application as new functionality is added; Application functionality and modules
should be independent enough to test separately. done by programmers or by testers.

Integration testing - Testing of integrated modules to verify combined functionality after


integration. Modules are typically code modules, individual applications, client and
server applications on a network, etc. This type of testing is especially relevant to
client/server and distributed systems.

Functional testing - This type of testing ignores the internal parts and focus on the
output is as per requirement or not. Black-box type testing geared to functional
requirements of an application.

System testing - Entire system is tested as per the requirements. Black-box type testing
that is based on overall requirements specifications, covers all combined parts of a
system.

End-to-end testing - Similar to system testing, involves testing of a complete application


environment in a situation that mimics real-world use, such as interacting with a
database, using network communications, or interacting with other hardware,
applications, or systems if appropriate.

Sanity testing - Testing to determine if a new software version is performing well


enough to accept it for a major testing effort. If application is crashing for initial use then
system is not stable enough for further testing and build or application is assigned to fix.

Regression testing - Testing the application as a whole for the modification in any
module or functionality. Difficult to cover all the system in regression testing so typically
automation tools are used for these testing types.

Acceptance testing -Normally this type of testing is done to verify if system meets the
customer specified requirements. User or customer do this testing to determine whether
to accept application.

Page 17
Junit

Load testing - Its a performance testing to check system behavior under load. Testing an
application under heavy loads, such as testing of a web site under a range of loads to
determine at what point the system’s response time degrades or fails.

Stress testing - System is stressed beyond its specifications to check how and when it
fails. Performed under heavy load like putting large number beyond storage capacity,
complex database queries, continuous input to system or database load.

Performance testing - Term often used interchangeably with ’stress’ and ‘load’ testing.
To check whether system meets performance requirements. Used different performance
and load tools to do this.

Usability testing - User-friendliness check. Application flow is tested, Can new user
understand the application easily, Proper help documented whenever user stuck at any
point. Basically system navigation is checked in this testing.

Install/uninstall testing - Tested for full, partial, or upgrade install/uninstall processes on


different operating systems under different hardware, software environment.

Recovery testing - Testing how well a system recovers from crashes, hardware failures,
or other catastrophic problems.

Security testing - Can system be penetrated by any hacking way. Testing how well the
system protects against unauthorized internal or external access. Checked if system,
database is safe from external attacks or not.

Compatibility testing - Testing how well software performs in a particular


hardware/software/operating system/network environment and different combination s of
above.

Comparison testing - Comparison of product strengths and weaknesses with previous


versions or other similar products.

Alpha testing - In house virtual user environment can be created for this type of testing.
Testing is done at the end of development. Still minor design changes may be made as a
result of such testing.

Beta testing - Testing typically done by end-users or others. Final testing before releasing
application for commercial purpose.

Get from http://www.softwaretestinghelp.com/types-of-software-testing/

Page 18
Junit

Internationalization Testing
API Testing

Additional site for testing:


http://www.testinggeek.com/index.php/testing-types

Some Examples
Listing 1

import junit.framework.TestCase;
import org.junit.Test;
import org.junit.Before;

import dk.unwire.apps.tellafriend.tools.Msisdn;

public class MsisdenTest extends TestCase {

@Before
public void init() {
this.msisdn = new Msisdn();
}

@Test
public void msisdnStringRightDigitTest() {
this.msisdn = new Msisdn();
assertEquals(true, this.msisdn.IsRightString("123467"));
}

public void msisdnStringWrongDigitTest() {


assertNotSame(true, this.msisdn.IsRightString("123467m"));
}

private Msisdn msisdn;

Listing 2

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

public class SimpleTest {

Page 19
Junit

private Collection<String> collection;

@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
}

@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
}

@Before
public void setUp() {
collection = new ArrayList<String>();
}

@After
public void tearDown() {
collection.clear();
}

@Test
public void testEmptyCollection() {
assertTrue(collection.isEmpty());
}

@Test
public void testOneItemCollection() {
collection.add("itemA");
assertEquals(1, collection.size());
}
}

Listing 3
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularTestMain {

/**
* @param args
*/
public static void main(String[] args) {

Pattern p = Pattern.compile("[0-9]*");
Matcher m = p.matcher("121212");
System.out.println( m.matches()+" p3");
}

Page 20
Junit

FEEDBACK
• Please send your feedback/question to
martin_m_nad@yahoo.com

DONATION

If you like this documentation and it was


helpful you can just donate 7$ by using this
https://www.paypal.com/cgi-bin/webscr?cmd=_s-
or use this to put
xclick&hosted_button_id=5814019
any amont you like to donate
https://www.paypal.com/cgi-bin/webscr?cmd=_s-
xclick&hosted_button_id=5813954 and if it doesn’t work copy
the link and put it on your browser.

if it doesn’t work copy the link and put it on your browser.

Page 21
Junit

My other documentation

Properties in Java and Spring by Martin Nad


Spring and Cxf by Example
Jboss and Perm Gen Error
Using Ftp Service With Spring
JunIt
How to use Maven
ReFactoring
Maven and Custome Archetype
How to Write Effective Code
How to use caching system in java

Page 22

You might also like