JUnit by Raghu Sir
JUnit by Raghu Sir
JUnit (4.X)
Coding (or) Implementation of module/task is done by developer. After
Coding is done it will be submitted to Testing Team (QA=Quality Analysis Team).
QA Team may do different types of testing. But before submitting code to QA, if
DEV performs Individual tasks/modules tested then Error(BUG) rate will be
reduced in Application.
Programmer cannot test complete project he can test only his module or
task that is called as Unit Testing. Here Unit Indicates a class, method, one layer,
one module etc..
JUnit Supports two types of Programs for Unit Testing those are:
1. Test Case (one module/part check) : It is a class used to write test methods
which confirms the code working functionality. It returns test PASS/FAIL.
On running Test case, result will be shown on JUnit Console.
2. Test Suite (One or multiple Test cases) : It is also a class, It is a collection of
multiple Test Cases together to run all test cases at a time.
1
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
To Write JUnit Test case we need to know two important concepts. Those
are Annotations in JUnit and Assert (C) API which has all test methods (static),
those are also called as assert methods.
Annotations in JUnit:
Creating a JUnit Test case :- One test case is used to test one module or task
mainly. Naming Rule is mainly followed in development bit it is optional. class
name must look like "Test<Module name>".
2
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
ex: for Employee module Test case is :TestEmployee. Like other examples are
TestAdmin, TestLocation.
In this Example we are using a Maven project here. Maven supports in-built
design of JUnit Test Programming.
Screen : 1
Screen : 2
3
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Screen : 3
Screen : 4
4
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Screen : 5
Screen : 6
Screen : 7
5
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Screen : 8
Note:
package com.app.test;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
6
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
@BeforeClass
public static void onetimeBefore(){
System.out.println("Before All..");
}
@Before
public void preWork(){
System.out.println("before..");
}
@Test
public void testA() {
System.out.println("Test-1");
}
@Test
public void testB() {
System.out.println("Test-2");
}
@Test
public void testC() {
System.out.println("Test-3");
}
@After
public void postWork(){
System.out.println("After..");
}
@AfterClass
public static void ontimeAfter(){
System.out.println("After All..");
}
}
static import in java: To use one class in another class, if both are in different
packages, then we must write import statement. import syntax:
import package.className;
If we use import statement , it will import all members (static and non-static)
Sometimes we need only static data then if we use normal import it will load all
members and waste then memory hence app performance will be reduced. To
7
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
load only static members (static variables and static methods) use static import
concept.
Example:
package com.app;
public class A{
int id;
String name;
static int pid =3;
void m1() { ... }
static void m2(){ ... }
}
From above class if we want load only static propeties into JVM then use
" import static com.app.A.* "
package com.one;
import static com.app.A.*;
public class B{
void show() {
sysout(pid);
m2(); //method call
}
}
To validate any application Logic we use Assert API methods, which are also
called as UnitTesting methods.
All these methods are static and void methods. These throws Assertion
Error in fail These methods will tell "Is Test PASS or FAIL?" only.
assertEquals("exp", "original");
assertEquals("MSG","exp", "org");
assertNotEquals("exp", "org");
assertNotEquals("MSG","exp", "org");
assertTrue(5>(8+9)/5)
(boolean condition)
assertTrue("Seems False..",5>(8+9)/5);
assertFalse(5>(8+9)/5);
assertFalse("Might be True",5>(8+9)/5);
fail();fail("Falied method test");
assertSame(ob1, ob2);
assertSame("not same..",ob1, ob2);
assertNotSame(ob1, ob2);
assertNotSame("same..",ob1, ob2);
Example#1:
Requirement : Develop one class with method that performs sum operation.
9
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Test : Test Above method using JUnitTest case with some random data.
Folder Structure:
Code : Requirement
package com.app.dev;
Create one JUnit Test case to verify that above code written properly or not.
package com.app.test;
import com.app.dev.Operations;
10
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
@Before
public void preSetup(){
opr=new Operations();
val1=val2=1;
exp=2;
}
@Test
public void test() {
int res=opr.doSum(val1, val2);
assertEquals(
"Dosum is not working",exp,res);
}
@After
public void postTest(){
opr=null; val1=val2=exp=0;
}
}
11
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Example:-
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
....// @Test
12
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
pom.xml code:-
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sathatech</groupId>
<artifactId>JUnitApps</artifactId>
<version>1.0</version>
13
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
Create one Properties for all key=value, for email and Database connection.
Right click on "src/main/resources" folder , then goto new and select other
Search with "file" option and select file , click next button
14
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
app.properties (code)
#DB Properties
dc=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
un=root
pwd=root
#mail
[email protected]
password=Asdfghjkl1@
AuthKey=mail.smtp.auth
TLSKey=mail.smtp.starttls.enable
HostKey=mail.smtp.host
PortKey=mail.smtp.port
import java.sql.Connection;
15
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
import java.sql.DriverManager;
Class.forName(getProperties().getProperty("dc"));
con=DriverManager.getConnection(getProperties().getPrope
rty("url"),
getProperties().getProperty("un"),
getProperties().getProperty("pwd"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getSingeltonConnection(){
return con;
}
}
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.app.dev.ConnectionUtil;
16
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Connection con1,con2;
@Before
public void setUp(){
con1=ConnectionUtil.getSingeltonConnection();
con2=ConnectionUtil.getSingeltonConnection();
}
@Test
public void test() {
assertNotNull(con1);
assertNotNull(con2);
assertSame("Not a singleton connection",con1,
con2);
}
@After
public void clear(){
con1=con2=null;
}
}
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
17
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
try {
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
18
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
isMailSent=false;
e.printStackTrace();
}
return isMailSent;
}
}
package com.app.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.app.dev.MailService;
String toAddr,sub,text;
@Before
public void setUp(){
toAddr="[email protected]";
sub="TESTAAA";
text="HEllo..";
}
@Test(timeout=5*1000)
public void test() {
boolean flag=MailService.sendEmail(toAddr, sub, text);
assertTrue(flag);
}
@After
public void clean(){
toAddr="[email protected]";
sub="TEST";
text="HEllo..";
19
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
}
}
package com.app.dev;
package com.app.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.app.dev.Mathematics;
20
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
int num;
@Before
public void preSet(){
num=548834;
//http://mathworld.wolfram.com/NarcissisticNumber.html
}
@Test
public void test() {
boolean flag=Mathematics.isArmStrong(num);
assertTrue(flag);
}
@After
public void postModify(){
num=0;
}
4. Input String following ABC Cycle or not: String should follow Cycle
package com.app.dev;
return flag;
}
private static Character getNext(char c){
if(c=='A') c= 'B';
else if(c=='B') c= 'C';
else if(c=='C') c= 'A';
return c;
}
package com.app.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.app.dev.StringOpers;
String str;
@Before
public void setStr(){
str="CABCA";
}
@Test
public void test() {
assertTrue(StringOpers.isFollwingABCCycle(str));
}
@After
public void clean(){
22
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
str=null;
}
}
Test Suite :
In JUnit, only one Test cases can be run at a time. If we want to run multiple
Test cases at a time , then we need to create a JUnit Test suite. Every Suite must
contain minimum one Test Case to Run.
Suite Also Follows naming convention which also optional. Test suite also a
class but it has no logical method to execute. Test Suite class name must be
suffixed with Tests word. Example AllTests.
Screen : 1
23
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
Screen : 2
Screen : 3
Screen : 4
24
Raghu Sir (JUnit 4.x) Sathya Technologies, Ameerpet.
package com.app.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ TestConnectionUtil.class,
TestMailService.class, TestMathematics.class,
TestStringOpers.class })
public class AllTests {
To Run Suite : Right click on code (Editor) , choose Run As, JUnit Test.
25