SlideShare a Scribd company logo
1 of 40
Java. Unit and
Integration Testing
IT Academy
22/07/2014
Agenda
▪Unit and Integration Testing
▪JUnit
▪TestNG
▪Parallel Tests Running
▪Case studies
Testing Types. Unit Testing
▪ Unit testing is a procedure used to validate that individual
units of source code are working properly.
▪ The goal of unit testing is to isolate each part of the program
and show that the individual parts are correct.
Integration Testing
▪ Integration testing is the phase of software testing in which
individual software modules are combined and tested as a
group.
▪ This is testing two or more modules or functions together with
the intent of finding interface defects between the modules or
functions.
Integration Testing
▪ Task: Database scripts, application main code and GUI
components were developed by different programmers. There
is need to test the possibility to use these 3 parts as one
system.
▪ Integration Testing Procedure: Combine 3 parts into one
system and verify interfaces (check interaction with database
and GUI).
▪ Defect: “Materials” button action returns not list of books but
list of available courses.
Unit / Integration Testing
public class One {
private String text;
public One() {
// Code
}
// Functionality
public int calc() {
int result = 0;
// Code
return result;
}
// get, set, etc.
}
Unit / Integration Testing
public class Two {
private One one;
public Two(One one) {
this.one = one;
}
public String resume() {
// Functionality
return one.getText() + "_" + one.calc().toString();
}
// Code
}
Unit / Integration Testing
public class Appl {
public static void main(String[] args) {
One one = new One();
one.setText("data“);
Two two = new Two(one);
two.resume();
// etc
}
}
Unit / Integration Testing
public class TwoTest {
@Test
public void TestResume() {
One one = new One();
one.setText("Integration Test“);
Two two = new Two(one);
// TODO Initialize to an appropriate value
String expected = "Integration Test_..."; // Result ???
String actual;
actual = two.resume();
Assert.AreEqual(expected, actual);
} }
Unit / Integration Testing
▪ A method stub or simply stub in software development is a
piece of code used to stand in for some other programming
functionality.
▪ A stub may simulate the behavior of existing code or be a
temporary substitute for yet-to-be-developed code.
public interface IOne {
void setText(String text);
String getText();
int calc();
}
Unit / Integration Testing
public class One implements IOne {
private String text;
public One() {
// Code
}
// Functionality
public int calc() {
int result = 0;
// Code
return result;
}
// get, set, etc.
}
Unit / Integration Testing
public class Two {
private IOne one;
public Two(IOne one) {
this.one = one;
}
public String resume() {
// Functionality
return one.getText() + "_" + one.calc().toString();
}
// Code
}
Unit / Integration Testing
▪ Stub – a piece of code used to stand in for some other
programming functionality.
public class StubOne extends IOne {
private String text;
public StubOne() {
}
public void setText(String text) {
}
public String getText() {
return “”
}
public int Calc() {
return 0;
}
}
Unit / Integration Testing
public class TwoTest {
@Test
public void TestResume() {
IOne one = new StubOne();
one.setText(" Unit Test“);
Two two = new Two(one);
// TODO Initialize to an appropriate value
String expected = " Unit Test_..."; // Result !!!
String actual;
actual = two.resume();
Assert.AreEqual(expected, actual);
} }
Junit 3
import junit.framework.TestCase;
рublic class AddJavaTest extends TestCase {
protected void setUp() throws Exception {
// create object }
protected void tearDown() throws Exception {
// to free resources }
public AddJavaTest(String name){
super (name); }
public void testSimpleAddition( ){
assertTrue(expect == actual);
} }
▪deprecated
JUnit
Assert class contains many different overloaded methods.
http://www.junit.org/ https
://github.com/kentbeck/junit/wiki
assertEquals(long expected, long actual)
Asserts that two longs are equal.
assertTrue(boolean condition)
Asserts that a condition is true.
assertFalse(boolean condition)
Asserts that a condition is false.
assertNotNull(java.lang.Object object)
Asserts that an object isn't null.
assertNull(java.lang.Object object)
Asserts that an object is null.
JUnit
assertSame(java.lang.Object expected,
java.lang.Object actual)
Asserts that two objects refer to the same object.
assertNotSame(java.lang.Object unexpected,
java.lang.Object actual)
Asserts that two objects do not refer to the same object.
assertArrayEquals(byte[] expecteds,
byte[] actuals)
Asserts that two byte arrays are equal.
fail()
Fails a test with no message.
fail(java.lang.String message)
Fails a test with the given message.
Junit 4
import org.junit.Test;
import org.junit.Assert;
public class MathTest {
@Test
public void testEquals( ) {
Assert.assertEquals(4, 2 + 2);
Assert.assertTrue(4 == 2 + 2);
}
@Test
public void testNotEquals( ) {
Assert.assertFalse(5 == 2 + 2);
} }
JUnit
JUnit
JUnit
JUnit
TestNG
▪ JUnit 4 and TestNG are both very popular unit test framework
in Java.
▪ TestNG (Next Generation) is a testing framework which
inspired by JUnit and NUnit, but introducing many new
innovative functionality like dependency testing, grouping
concept to make testing more powerful and easier to do. It is
designed to cover all categories of tests: unit, functional, end-
to-end, integration, etc.
TestNG
▪ Setting up TestNG with Eclipse.
▪ Click Help –> Install New Software
▪ Type http://beust.com/eclipse in the "Work with" edit box and
click ‘Add’ button.
▪ Click Next and click on the radio button "I accept the terms of
the license agreement“.
▪ After the installation, it will ask for restart of Eclipse. Then
restart the Eclipse.
▪ Once the Eclipse is restarted, we can see the TestNG icons &
menu items as in the below figures.
TestNG
▪ To create a new TestNG class, select the menu
File/New/TestNG
TestNG
▪ The next page lets you specify where that file will be created
TestNG
▪ Basic usage
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNGTest1 {
private Collection collection;
@BeforeClass
public void oneTimeSetUp() {
System.out.println("@BeforeClass - oneTimeSetUp"); }
@AfterClass
public void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown"); }
TestNG
@BeforeMethod
public void setUp() {
collection = new ArrayList();
System.out.println("@BeforeMethod - setUp");
}
@AfterMethod
public void tearDown() {
collection.clear();
System.out.println("@AfterMethod - tearDown");
}
TestNG
@Test
public void testEmptyCollection() {
Assert.assertEquals(collection.isEmpty(),true);
System.out.println("@Test - testEmptyCollection");
}
@Test
public void testOneItemCollection() {
collection.add("itemA");
Assert.assertEquals(collection.size(),1);
System.out.println("@Test - testOneItemCollection");
}
}
TestNG
▪ Expected Exception Test
▪ The divisionWithException() method will throw an
ArithmeticException Exception, since this is an expected
exception, so the unit test will pass.
import org.testng.annotations.*;
public class TestNGTest2 {
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
}
TestNG
▪ Suite Test. The “Suite Test” means bundle a few unit test cases
and run it together.
▪ In TestNG, XML file is use to define the suite test.
<!DOCTYPE suite SYSTEM
"http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<classes>
<class name="TestNGTest1" />
<class name="TestNGTest2" />
</classes>
</test>
</suite>
▪"TestNGTest1" and "TestNGTest2" will
execute together
TestNG
▪ Parameterized Test
▪ In TestNG, XML file or “@DataProvider” is used to provide
vary parameter for unit testing.
▪ Declare “@Parameters” annotation in method which needs
parameter testing, the parametric data will be provide by
TestNG’s XML configuration files. By doing this, you can reuse
a single test case with different data sets easily.
import org.testng.annotations.*;
public class TestNGTest6 {
@Test
@Parameters(value="number")
public void parameterIntTest(int number) {
System.out.println("Parameterized Number is: " +
number);
} }
TestNG
<!DOCTYPE suite SYSTEM
"http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<parameter name="number" value="2"/>
<classes>
<class name="TestNGTest6" />
</classes>
</test>
</suite>
Result: Parameterized Number is : 2
TestNG
▪ Testing example. Converting the character to ASCII or vice
verse.
package com.softserve.edu;
public class CharUtils
{
public static int CharToASCII(final char character){
return (int)character;
}
public static char ASCIIToChar(final int ascii){
return (char)ascii;
}
}
TestNG
import org.testng.Assert;
import org.testng.annotations.*;
public class CharUtilsTest {
@DataProvider
public Object[][] ValidDataProvider() {
return new Object[][]{
{ 'A', 65 }, { 'a', 97 },
{ 'B', 66 }, { 'b', 98 },
{ 'C', 67 }, { 'c', 99 },
{ 'D', 68 }, { 'd', 100 },
{ 'Z', 90 }, { 'z', 122 },
{ '1', 49 }, { '9', 57 }, };
}
TestNG
@Test(dataProvider = "ValidDataProvider")
public void CharToASCIITest(final char character,
final int ascii) {
int result = CharUtils.CharToASCII(character);
Assert.assertEquals(result, ascii); }
@Test(dataProvider = "ValidDataProvider")
public void ASCIIToCharTest(final char character,
final int ascii) {
char result = CharUtils.ASCIIToChar(ascii);
Assert.assertEquals(result, character);
} }
TestNG
▪ Dependency Test. TestNG uses “dependOnMethods“ to
implement the dependency testing. If the dependent method
fails, all the subsequent test methods will be skipped, not
marked as failed.
▪ The “method2()” will execute only if “method1()” is run
successfully, else “method2()” will skip
import org.testng.annotations.*;
public class TestNGTest10 {
@Test
public void method1() {
System.out.println("This is method 1"); }
@Test(dependsOnMethods={"method1"})
public void method2() {
System.out.println("This is method 2"); } }
TestNG
public class ConcurrencyTest2 extends Assert {
// some staff here
@DataProvider(parallel = true)
public Object[][] concurrencyData() {
return new Object[][] {
{"1", "2"}, {"3", "4"},
{"5", "6"}, {"7", "8"},
{"9", "10"}, {"11", "12"},
{"13", "14"}, {"15", "16"},
{"17", "18"}, {"19", "20"},
};
}
TestNG
▪ Set parallel option at the date of the provider in true.
▪ Tests for each data set to be launched in a separate thread.
@Test(dataProvider = "concurrencyData")
public void testParallelData(String first, String second) {
final Thread thread = Thread.currentThread();
System.out.printf("#%d %s: %s : %s", thread.getId(),
thread.getName(), first, second);
System.out.println();
}
}
Junit and testNG

More Related Content

What's hot

TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingBethmi Gunasekara
 
Introduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkIntroduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkBugRaptors
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PBAbhishek Yadav
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Kiki Ahmadi
 
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 JanardhanaRavikiran J
 

What's hot (20)

Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
TestNg_Overview_Config
TestNg_Overview_ConfigTestNg_Overview_Config
TestNg_Overview_Config
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Introduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit frameworkIntroduction of TestNG framework and its benefits over Junit framework
Introduction of TestNG framework and its benefits over Junit framework
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
Test ng
Test ngTest ng
Test ng
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Test ng
Test ngTest ng
Test ng
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
Junit
JunitJunit
Junit
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
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
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 

Viewers also liked

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Maven TestNg frame work (1) (1)
Maven TestNg frame work (1) (1)Maven TestNg frame work (1) (1)
Maven TestNg frame work (1) (1)Gopi Raghavendra
 
Me and my goals
Me and my goalsMe and my goals
Me and my goalsgabydq
 
Berntsen -chicago_my_home_town_-_08-10-11
Berntsen  -chicago_my_home_town_-_08-10-11Berntsen  -chicago_my_home_town_-_08-10-11
Berntsen -chicago_my_home_town_-_08-10-11Rosanna Goode
 
TOPTEN Mediakit For New Home Builders
TOPTEN Mediakit For New Home BuildersTOPTEN Mediakit For New Home Builders
TOPTEN Mediakit For New Home BuildersJonathan Wilhelm
 
pay it foward
pay it fowardpay it foward
pay it fowardgabydq
 
Ad Tracker Report
Ad Tracker ReportAd Tracker Report
Ad Tracker ReportPaul Green
 
Green fax agm
Green fax  agm Green fax  agm
Green fax agm Paul Green
 
05 junit
05 junit05 junit
05 junitmha4
 
人工知能の研究開発方法について20160927
人工知能の研究開発方法について20160927人工知能の研究開発方法について20160927
人工知能の研究開発方法について20160927和明 宮本
 

Viewers also liked (16)

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Maven TestNg frame work (1) (1)
Maven TestNg frame work (1) (1)Maven TestNg frame work (1) (1)
Maven TestNg frame work (1) (1)
 
Me and my goals
Me and my goalsMe and my goals
Me and my goals
 
Berntsen -chicago_my_home_town_-_08-10-11
Berntsen  -chicago_my_home_town_-_08-10-11Berntsen  -chicago_my_home_town_-_08-10-11
Berntsen -chicago_my_home_town_-_08-10-11
 
Ad tracker
Ad trackerAd tracker
Ad tracker
 
TOPTEN Mediakit For New Home Builders
TOPTEN Mediakit For New Home BuildersTOPTEN Mediakit For New Home Builders
TOPTEN Mediakit For New Home Builders
 
Green Fax Agm
Green Fax  AgmGreen Fax  Agm
Green Fax Agm
 
Educ1751 Assignment 1
Educ1751 Assignment 1Educ1751 Assignment 1
Educ1751 Assignment 1
 
Git
GitGit
Git
 
pay it foward
pay it fowardpay it foward
pay it foward
 
Ad Tracker Report
Ad Tracker ReportAd Tracker Report
Ad Tracker Report
 
Logging
LoggingLogging
Logging
 
Green fax agm
Green fax  agm Green fax  agm
Green fax agm
 
05 junit
05 junit05 junit
05 junit
 
Junit
JunitJunit
Junit
 
人工知能の研究開発方法について20160927
人工知能の研究開発方法について20160927人工知能の研究開発方法について20160927
人工知能の研究開発方法について20160927
 

Similar to Junit and testNG

Similar to Junit and testNG (20)

3 j unit
3 j unit3 j unit
3 j unit
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Presentation Unit Testing process
Presentation Unit Testing processPresentation Unit Testing process
Presentation Unit Testing process
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Android testing
Android testingAndroid testing
Android testing
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 

Recently uploaded

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Junit and testNG

  • 1. Java. Unit and Integration Testing IT Academy 22/07/2014
  • 2. Agenda ▪Unit and Integration Testing ▪JUnit ▪TestNG ▪Parallel Tests Running ▪Case studies
  • 3. Testing Types. Unit Testing ▪ Unit testing is a procedure used to validate that individual units of source code are working properly. ▪ The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.
  • 4. Integration Testing ▪ Integration testing is the phase of software testing in which individual software modules are combined and tested as a group. ▪ This is testing two or more modules or functions together with the intent of finding interface defects between the modules or functions.
  • 5. Integration Testing ▪ Task: Database scripts, application main code and GUI components were developed by different programmers. There is need to test the possibility to use these 3 parts as one system. ▪ Integration Testing Procedure: Combine 3 parts into one system and verify interfaces (check interaction with database and GUI). ▪ Defect: “Materials” button action returns not list of books but list of available courses.
  • 6. Unit / Integration Testing public class One { private String text; public One() { // Code } // Functionality public int calc() { int result = 0; // Code return result; } // get, set, etc. }
  • 7. Unit / Integration Testing public class Two { private One one; public Two(One one) { this.one = one; } public String resume() { // Functionality return one.getText() + "_" + one.calc().toString(); } // Code }
  • 8. Unit / Integration Testing public class Appl { public static void main(String[] args) { One one = new One(); one.setText("data“); Two two = new Two(one); two.resume(); // etc } }
  • 9. Unit / Integration Testing public class TwoTest { @Test public void TestResume() { One one = new One(); one.setText("Integration Test“); Two two = new Two(one); // TODO Initialize to an appropriate value String expected = "Integration Test_..."; // Result ??? String actual; actual = two.resume(); Assert.AreEqual(expected, actual); } }
  • 10. Unit / Integration Testing ▪ A method stub or simply stub in software development is a piece of code used to stand in for some other programming functionality. ▪ A stub may simulate the behavior of existing code or be a temporary substitute for yet-to-be-developed code. public interface IOne { void setText(String text); String getText(); int calc(); }
  • 11. Unit / Integration Testing public class One implements IOne { private String text; public One() { // Code } // Functionality public int calc() { int result = 0; // Code return result; } // get, set, etc. }
  • 12. Unit / Integration Testing public class Two { private IOne one; public Two(IOne one) { this.one = one; } public String resume() { // Functionality return one.getText() + "_" + one.calc().toString(); } // Code }
  • 13. Unit / Integration Testing ▪ Stub – a piece of code used to stand in for some other programming functionality. public class StubOne extends IOne { private String text; public StubOne() { } public void setText(String text) { } public String getText() { return “” } public int Calc() { return 0; } }
  • 14. Unit / Integration Testing public class TwoTest { @Test public void TestResume() { IOne one = new StubOne(); one.setText(" Unit Test“); Two two = new Two(one); // TODO Initialize to an appropriate value String expected = " Unit Test_..."; // Result !!! String actual; actual = two.resume(); Assert.AreEqual(expected, actual); } }
  • 15. Junit 3 import junit.framework.TestCase; рublic class AddJavaTest extends TestCase { protected void setUp() throws Exception { // create object } protected void tearDown() throws Exception { // to free resources } public AddJavaTest(String name){ super (name); } public void testSimpleAddition( ){ assertTrue(expect == actual); } } ▪deprecated
  • 16. JUnit Assert class contains many different overloaded methods. http://www.junit.org/ https ://github.com/kentbeck/junit/wiki assertEquals(long expected, long actual) Asserts that two longs are equal. assertTrue(boolean condition) Asserts that a condition is true. assertFalse(boolean condition) Asserts that a condition is false. assertNotNull(java.lang.Object object) Asserts that an object isn't null. assertNull(java.lang.Object object) Asserts that an object is null.
  • 17. JUnit assertSame(java.lang.Object expected, java.lang.Object actual) Asserts that two objects refer to the same object. assertNotSame(java.lang.Object unexpected, java.lang.Object actual) Asserts that two objects do not refer to the same object. assertArrayEquals(byte[] expecteds, byte[] actuals) Asserts that two byte arrays are equal. fail() Fails a test with no message. fail(java.lang.String message) Fails a test with the given message.
  • 18. Junit 4 import org.junit.Test; import org.junit.Assert; public class MathTest { @Test public void testEquals( ) { Assert.assertEquals(4, 2 + 2); Assert.assertTrue(4 == 2 + 2); } @Test public void testNotEquals( ) { Assert.assertFalse(5 == 2 + 2); } }
  • 19. JUnit
  • 20. JUnit
  • 21. JUnit
  • 22. JUnit
  • 23. TestNG ▪ JUnit 4 and TestNG are both very popular unit test framework in Java. ▪ TestNG (Next Generation) is a testing framework which inspired by JUnit and NUnit, but introducing many new innovative functionality like dependency testing, grouping concept to make testing more powerful and easier to do. It is designed to cover all categories of tests: unit, functional, end- to-end, integration, etc.
  • 24. TestNG ▪ Setting up TestNG with Eclipse. ▪ Click Help –> Install New Software ▪ Type http://beust.com/eclipse in the "Work with" edit box and click ‘Add’ button. ▪ Click Next and click on the radio button "I accept the terms of the license agreement“. ▪ After the installation, it will ask for restart of Eclipse. Then restart the Eclipse. ▪ Once the Eclipse is restarted, we can see the TestNG icons & menu items as in the below figures.
  • 25. TestNG ▪ To create a new TestNG class, select the menu File/New/TestNG
  • 26. TestNG ▪ The next page lets you specify where that file will be created
  • 27. TestNG ▪ Basic usage import java.util.*; import org.testng.Assert; import org.testng.annotations.*; public class TestNGTest1 { private Collection collection; @BeforeClass public void oneTimeSetUp() { System.out.println("@BeforeClass - oneTimeSetUp"); } @AfterClass public void oneTimeTearDown() { // one-time cleanup code System.out.println("@AfterClass - oneTimeTearDown"); }
  • 28. TestNG @BeforeMethod public void setUp() { collection = new ArrayList(); System.out.println("@BeforeMethod - setUp"); } @AfterMethod public void tearDown() { collection.clear(); System.out.println("@AfterMethod - tearDown"); }
  • 29. TestNG @Test public void testEmptyCollection() { Assert.assertEquals(collection.isEmpty(),true); System.out.println("@Test - testEmptyCollection"); } @Test public void testOneItemCollection() { collection.add("itemA"); Assert.assertEquals(collection.size(),1); System.out.println("@Test - testOneItemCollection"); } }
  • 30. TestNG ▪ Expected Exception Test ▪ The divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass. import org.testng.annotations.*; public class TestNGTest2 { @Test(expectedExceptions = ArithmeticException.class) public void divisionWithException() { int i = 1/0; } }
  • 31. TestNG ▪ Suite Test. The “Suite Test” means bundle a few unit test cases and run it together. ▪ In TestNG, XML file is use to define the suite test. <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" > <suite name="My test suite"> <test name="testing"> <classes> <class name="TestNGTest1" /> <class name="TestNGTest2" /> </classes> </test> </suite> ▪"TestNGTest1" and "TestNGTest2" will execute together
  • 32. TestNG ▪ Parameterized Test ▪ In TestNG, XML file or “@DataProvider” is used to provide vary parameter for unit testing. ▪ Declare “@Parameters” annotation in method which needs parameter testing, the parametric data will be provide by TestNG’s XML configuration files. By doing this, you can reuse a single test case with different data sets easily. import org.testng.annotations.*; public class TestNGTest6 { @Test @Parameters(value="number") public void parameterIntTest(int number) { System.out.println("Parameterized Number is: " + number); } }
  • 33. TestNG <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" > <suite name="My test suite"> <test name="testing"> <parameter name="number" value="2"/> <classes> <class name="TestNGTest6" /> </classes> </test> </suite> Result: Parameterized Number is : 2
  • 34. TestNG ▪ Testing example. Converting the character to ASCII or vice verse. package com.softserve.edu; public class CharUtils { public static int CharToASCII(final char character){ return (int)character; } public static char ASCIIToChar(final int ascii){ return (char)ascii; } }
  • 35. TestNG import org.testng.Assert; import org.testng.annotations.*; public class CharUtilsTest { @DataProvider public Object[][] ValidDataProvider() { return new Object[][]{ { 'A', 65 }, { 'a', 97 }, { 'B', 66 }, { 'b', 98 }, { 'C', 67 }, { 'c', 99 }, { 'D', 68 }, { 'd', 100 }, { 'Z', 90 }, { 'z', 122 }, { '1', 49 }, { '9', 57 }, }; }
  • 36. TestNG @Test(dataProvider = "ValidDataProvider") public void CharToASCIITest(final char character, final int ascii) { int result = CharUtils.CharToASCII(character); Assert.assertEquals(result, ascii); } @Test(dataProvider = "ValidDataProvider") public void ASCIIToCharTest(final char character, final int ascii) { char result = CharUtils.ASCIIToChar(ascii); Assert.assertEquals(result, character); } }
  • 37. TestNG ▪ Dependency Test. TestNG uses “dependOnMethods“ to implement the dependency testing. If the dependent method fails, all the subsequent test methods will be skipped, not marked as failed. ▪ The “method2()” will execute only if “method1()” is run successfully, else “method2()” will skip import org.testng.annotations.*; public class TestNGTest10 { @Test public void method1() { System.out.println("This is method 1"); } @Test(dependsOnMethods={"method1"}) public void method2() { System.out.println("This is method 2"); } }
  • 38. TestNG public class ConcurrencyTest2 extends Assert { // some staff here @DataProvider(parallel = true) public Object[][] concurrencyData() { return new Object[][] { {"1", "2"}, {"3", "4"}, {"5", "6"}, {"7", "8"}, {"9", "10"}, {"11", "12"}, {"13", "14"}, {"15", "16"}, {"17", "18"}, {"19", "20"}, }; }
  • 39. TestNG ▪ Set parallel option at the date of the provider in true. ▪ Tests for each data set to be launched in a separate thread. @Test(dataProvider = "concurrencyData") public void testParallelData(String first, String second) { final Thread thread = Thread.currentThread(); System.out.printf("#%d %s: %s : %s", thread.getId(), thread.getName(), first, second); System.out.println(); } }