SlideShare ist ein Scribd-Unternehmen logo
1 von 50
By Sanjib Dhar
8/13/2013 techniqpatch.blogspot.com 1
Why & What is Unit Testing
 Testing is the process of checking the functionality of
the application whether it is working as per
requirements and to ensure that at developer
level, unit testing comes into picture. Unit testing is
the testing of single entity (class or method). Unit
testing is very essential to every software company to
give a quality product to their customers.
 It ensures the delivery of right product with right
functionality.
8/13/2013 techniqpatch.blogspot.com 2
What is JUnit ?
 JUnit is a Regression Testing Framework* for the Java
Programming Language. It is important in the test driven
development, and is one of a family of unit testing
frameworks collectively known as xUnit.
*One of the main reasons for regression testing is to
determine whether a change in one part of the software
affects other parts of the software
8/13/2013 techniqpatch.blogspot.com 3
How it works !!!
 The idea is first testing then coding.
 Test a little , code a little, test a little,
code a little ,……
8/13/2013 techniqpatch.blogspot.com 4
Features
 JUnit is an open source framework
 Provides Annotation to identify the test methods.
 Provides Assertions for testing expected results.
 Provides Test runners for running tests.
 Simple and easy to write.
8/13/2013 techniqpatch.blogspot.com 5
What is Test case ??
 A test case in software engineering is a set of
conditions or variables under which a tester will
determine whether an application or software system
is working properly or not.
 A test case definition include the following
information :
 pre-conditions
 Set of input values
 Set of expected results
 How to execute the test and check results
 Expected post-conditions.
8/13/2013 techniqpatch.blogspot.com 6
Test case in JUnit !!!
 A Unit Test Case is a part of code which ensures that
the another part of code (method) works as expected.
 A formal written unit test case is characterized by a
known input and by an expected output.
 There must be at least two unit test cases for each
requirement: one positive test and one negative test.
8/13/2013 techniqpatch.blogspot.com 7
JUnit - Environment Setup
 First setup jdk.
 Set the environment variable JUNIT_HOME to
C:JUNIT .
 Set the environment variable CLASSPATH to
%CLASSPATH%;%JUNIT_HOME%junit4.10.jar;.;
 If you are using Eclipse , install the plug-in for JUnit.
8/13/2013 techniqpatch.blogspot.com 8
Component of JUnit
 JUnit test framework provides following important
features/component
Fixtures
Test suites
Test runners
JUnit classes
8/13/2013 techniqpatch.blogspot.com 9
Fixtures
 Fixtures is a fixed state of a set of objects used as a
baseline for running tests. The purpose of a test fixture
is to ensure that there is a well known and fixed
environment in which tests are run so that results are
repeatable. It includes
setUp() method which runs before every test
invocation.
tearDown() method which runs after every test
method.
8/13/2013 techniqpatch.blogspot.com 10
Fixture Example
import junit.framework.*;
public class JavaTest extends TestCase {
protected int value1, value2;
// assigning the values
protected void setUp(){
value1=2; value2=3;
}
// test method to add two values
@Test
public void testAdd(){
double result= value1 + value2;
assertTrue(result == 5);
}
protected void tearDown ()
{
//release resource
}
}
8/13/2013 techniqpatch.blogspot.com 11
Test Suite
 Test suite means bundle a few unit test cases and run
it together. In JUnit, both @RunWith and
@Suite annotation are used to run the suite test.
8/13/2013 techniqpatch.blogspot.com 12
Test Suite Example
Suite test class Classes to be tested
import
org.junit.runner.RunWi
th;
import
org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class, TestJun
it2.class }) public class
JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static
org.junit.Assert.assertEquals;
public class TestJunit1 {
String message = "Robert";
@Test
public void testPrintMessage() {
assertEquals(message,”hii”);
} }
//create another class as TestJunit2
8/13/2013 techniqpatch.blogspot.com 13
Test Runner
 Test runner is used for executing the test cases.
 Uses runClasses method of JUnitCore class of JUnit to
run test case of created test class.
 Gets the result of test cases run in Result Object.
 Gets failure(s) using getFailures() methods of Result
object.
 Gets Success result using wasSuccessful() methods of
Result object.
8/13/2013 techniqpatch.blogspot.com 14
Example of Test Runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
} System.out.println(result.wasSuccessful());
}
}
8/13/2013 techniqpatch.blogspot.com 15
JUnit API’s
 Assert
 TestCase
 TestResult
 TestSuite
8/13/2013 techniqpatch.blogspot.com 16
Assert
public class Assert extends java.lang.Object
This class provides a set of assertion methods useful for
writing tests. Only failed assertions are recorded. Some of
the important methods of Assert class are:
 void assertEquals(boolean expected, boolean actual)
 void assertFalse(boolean condition)
 void assertNotNull(Object object)
 void assertNull(Object object)
 void assertTrue(boolean condition)
 void fail()
 void assertSame(boolean condition)
 void assertNotSame(boolean condition)
8/13/2013 techniqpatch.blogspot.com 17
Assert Example
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions {
@Test
public void testAssertions() {
//test data
String str1 = new String (“sanjib");
String str2 = new String (“sanjib");
String str3 = null;
String str4 = "abc"; String str5 = "abc";
int val1 = 5; int val2 = 6;
String[] expectedArray = {"one", "two", "three"}; String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray); } }
8/13/2013 techniqpatch.blogspot.com 18
TestCase Class
public abstract class TestCase extends Assert implements Test
A test case defines the fixture to run multiple tests.Some important
method of this class are:
 int countTestCases() //Counts the number of test cases
 TestResult createResult()//Creates a default TestResult object.
 String getName() //Gets the name of a TestCase.
 TestResult run() //method to run thetest.
 void run(TestResult result) //Runs the test case and collects the
results in TestResult.
 void setName(String name)
 void setUp()//e.g. open a network connection.
 void tearDown() //e.g. close a network connection
8/13/2013 techniqpatch.blogspot.com 19
TestCase Example
package tv.seachange.ism.utils;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class TestCaseClass extends TestCase {
protected double val1,val2;
@Before
public void setUp() {
val1= 2.0;
val2= 3.0;
}
@Test
public void testAdd() {
System.out.println("No of Test Case = "+ this.countTestCases()); //count the number of test cases
String name= this.getName(); //test getName
System.out.println("Test Case Name = "+ name);
this.setName("newName"); //test setName
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
assertFalse(val1>val2);
}
public void tearDown( ) {//tearDown used to close the connection or clean up activities
}
}
8/13/2013 techniqpatch.blogspot.com 20
Test Result
 A TestResult collects the results of executing a test
case.Some of its methods are:
 void addError(Test test, Throwable t)//Adds an error to the list of
errors.
 void addFailure(Test test, AssertionFailedError t)//Adds a failure
to the list of failures.
 int errorCount()//Gets the number of detected errors.
 int failureCount()//Gets the number of detected failures.
 void run(TestCase test)//Runs a TestCase.
 void stop()//Marks that the test run should stop.
8/13/2013 techniqpatch.blogspot.com 21
TestSuite Class
 A TestSuite is a Composite of Tests. It runs a collection
of test cases. Some of the methods are
 void addTest(Test test)//Adds a test to the suite.
 int countTestCases()//Counts the number of test cases that will be
run by this test.
 String getName()//Returns the name of the suite.
 void setName(String name)//Sets the name of the suite.
 Test testAt(int index)//Returns the test at the given index.
8/13/2013 techniqpatch.blogspot.com 22
TestSuite Example
import junit.framework.*;
public class TestSuiteTest {
public static void main(String[] a) {
// add the test's in the suite
TestSuite suite = new
TestSuite(JunitTest1.class, JunitTest2.class, JunitTest3.class
);
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases = " +
result.runCount());
} }
8/13/2013 techniqpatch.blogspot.com 23
Execution Flow
 First of all beforeClass() method execute only once
 Lastly, the afterClass() method executes only once.
 before() method executes for each test case but before
executing the test case.
 after() method executes for each test case but after the
execution of test case
 In between before() and after() each test case executes.
8/13/2013 techniqpatch.blogspot.com 24
Execution Flow Example
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitExecutionFlow {
//execute only once, in the starting
@BeforeClass public static void beforeClass() {
System.out.println("in before class");
}
//execute only once, in the end
@AfterClass public static void afterClass() {
System.out.println("in after class");
}
//execute for each test, before executing test
@Before public void before() {
System.out.println("in before");
}
//execute for each test, after executing test
@After public void after() {
System.out.println("in after");
}
//test case 1
@Test public void testCase1() {
System.out.println("in test case 1"); }
//test case 2
@Test public void testCase2() { System.out.println("in test case 2");
}
}
8/13/2013 techniqpatch.blogspot.com 25
Ignore Test
 Sometimes it happens that our code is not ready and
test case written to test that method/code will fail if
run or we just don’t want to test that test case at that
moment. The @Ignore annotation helps in this
regards.
A test method annotated with @Ignore will not be
executed.
If a test class is annotated with @Ignore then all of its
test methods will be ignored.
8/13/2013 techniqpatch.blogspot.com 26
Ignored Test Example
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IgnoreTest {
@Test
public void notIgnored()
{
System.out.println("this is executed");
}
@Ignore
@Test
public void itIsIgnored()
{
System.out.println("This test is ignored");
}
}
8/13/2013 techniqpatch.blogspot.com 27
Time test
Junit provides a handy option of Timeout. If a test case
takes more time than specified number of
milliseconds then Junit will automatically mark it as
failed. The timeout parameter is used along with
@Test annotation.
8/13/2013 techniqpatch.blogspot.com 28
Time Test xample
import org.junit.Test;
public class TimeTest {
@Test(timeout=10)
public void testTime()
{
for(int i=0;i<1000;i++){
System.out.println("hiiiiii");
}
}
}
8/13/2013 techniqpatch.blogspot.com 29
Exception Test
 Junit provides a option of tracing the Exception
handling of code. You can test the code whether code
throws desired exception or not.
The expected parameter is used along with @Test
annotation.
8/13/2013 techniqpatch.blogspot.com 30
Exception Test Example
import org.junit.Test;
public class ExceptionTest {
@Test(expected=ArithmeticException.class)
public void exception()
{
int s=12/0;
}
}
8/13/2013 techniqpatch.blogspot.com 31
Parameterized Test
 Junit 4 has introduced a new feature Parameterized
tests.Parameterized tests allow developer to run the same
test over and over again using different values. There are
five steps, that you need to follow to create Parameterized
tests.
 Annotate test class with @RunWith(Parameterized.class)
 Create a public static method annotated with @Parameters that returns
a Collection of Objects (as Array) as test data set.
 Create a public constructor that takes in what is equivalent to one "row"
of test data.
 Create an instance variable for each "column" of test data.
 Create your tests case(s) using the instance variables as the source of
the test data.
8/13/2013 techniqpatch.blogspot.com 32
Parameterized Test Example
@RunWith(Parameterized.class)
public class ParameterizedTest {
private Integer inputNumber;
private Boolean expectedResult;
private OddEvenChecker oddEvenChecker;
@Before
public void initialize() {
oddEvenChecker = new OddEvenChecker();
}
public ParameterizedTest(Integer inputNumber,
Boolean expectedResult) {
this.inputNumber = inputNumber;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters
public static Collection checkNumbers() {
return Arrays.asList(new Object[][] {
{ 2, true },{ 6, true },{ 19, false },{ 22, true },{ 23, false }
});
}
@Test
public void testOddEvenChecker() {
System.out.println("Parameterized Number is : " + inputNumber);
assertEquals(expectedResult,
oddEvenChecker.checkNumber(inputNumber));
}
}
8/13/2013 techniqpatch.blogspot.com 33
Are we done ??
 Wow !! Now we know about Junit .But still some
question is there :
What if we want to test the dependency ? Or
What if we want to use Object as parameter not only
primitives ??
8/13/2013 techniqpatch.blogspot.com 34
Yes we can !!
 And the solution is TESTNG
8/13/2013 techniqpatch.blogspot.com 35
TestNG
 It stands for NEXT GENERATION JAVA TESTING.
 TestNG is a testing framework inspired
from JUnit and NUnit but introducing some new
functionalities in order to make it more powerful and
easier to use.
8/13/2013 techniqpatch.blogspot.com 36
Features of TestNG
 Annotations.
 Run your tests in arbitrarily big thread pools with various
policies available (all methods in their own thread, one
thread per test class, etc...).
 Flexible test configuration.
 Support for data-driven testing (with @DataProvider).
 Support for parameters.
 Powerful execution model (no more TestSuite).
 Supported by a variety of tools and plug-ins
(Eclipse, IDEA, Maven, etc...).
 Dependent methods for application server testing.
8/13/2013 techniqpatch.blogspot.com 37
Annotations
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNGTest1 {
private Collection collection;
@BeforeClass
public void oneTimeSetUp()
{ // one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp"); }
@AfterClass
public void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown"); }
@BeforeMethod
public void setUp() {
collection = new ArrayList();
System.out.println("@BeforeMethod - setUp"); }
@AfterMethod
public void tearDown() {
collection.clear();
System.out.println("@AfterMethod - tearDown"); }
@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");
} }
The annotations are :
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@Test
@BeforeTest
@AfterTest etc..
8/13/2013 techniqpatch.blogspot.com 38
Expected Exception Test
import org.testng.annotations.*;
public class TestNGTest2 {
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException()
{
int i = 1/0;
}
}
8/13/2013 techniqpatch.blogspot.com 39
Ignore and Time test
 In TestNG for ignoring a test below mention
annotation is used : @Test(enabled=false)
 For Time test the annotation is same as Junit.
@Test(timeOut = 1000)
8/13/2013 techniqpatch.blogspot.com 40
Suite or Grouping
 The grouping is used for running multiple test as a
group of tests. Unlike JUnit in TestNG we can make
different group of test method and can run single or
multiple group.
8/13/2013 techniqpatch.blogspot.com 41
Suite or Grouping Test
public class GroupingTest {
@Test(groups="group1")
public void testingGroup1 () {
System.out.println("Method - testingMethod1()"); }
@Test(groups="group2")
public void testingGroup2 () {
System.out.println("Method -
testingMethod2()"); }
@Test(groups="group1")
public void testingGroup1_1 () {
System.out.println("Method - testingMethod1_1()");
}
@Test(groups="group3")
public void testingGroup4() {
System.out.println("Method - testingMethod4()");
} }
8/13/2013 techniqpatch.blogspot.com 42
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM
"http://testng.org/testng-1.0.dtd"
>
<suite name="My suite">
<test name="testinggroup">
<groups>
<run>
<include name="group1"/>
</run>
</groups>
<classes>
<class name="GroupingTest"
/>
</classes>
</test>
</suite>
TestNG’s Parameterized Test
 TestNG’s Parameterized test is very user friendly and
flexible (either in XML file or inside the class). It can
support many complex data type as parameter value
and the possibility is unlimited. Moreover we even can
pass in our own object for Parameterized test.
8/13/2013 techniqpatch.blogspot.com 43
TestNG Parameterized Example
public class ParameterizedTest {
@Test(dataProvider =
"parameterizedDataProvider")
public void testParameter(User user,boolean
flag) {
System.out.println("the user name is
:"+user.getName());
System.out.println("the user id is
:"+user.getId());
}
@DataProvider(name="parameterizedDataProvi
der")
public Object[][] parameterizedDataProvider() {
return new Object[][] {
{new User("Sanjib",1),true},
{new User("Dhar",2),false}
}; }
}
class User{
private String name;
private int id;
public User() {
}
public User(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
8/13/2013 techniqpatch.blogspot.com 44
Dependency Test
 The TestNG has a feature called The “Dependency
Test”, means methods are tested base on dependency.
If the dependent method fails, all the subsequent test
methods will be skipped, not marked as failed.
8/13/2013 techniqpatch.blogspot.com 45
@DataProvider
 A Data Provider is a method annotated with
@DataProvider. This annotation has only one string
attribute: its name. If the name is not
supplied, theData Provider’s name automatically
defaults to the method’s name.
 A Data Provider returns Java objects that will be
passed as parameters to an @Test method. The name
of the Data Provider to receive parameters from is
specified in the dataProvider attribute of the @Test
annotation.
8/13/2013 techniqpatch.blogspot.com 46
Dependency Test example
public class DependencyTest {
@Test
public void test1() {
Object object = null;
System.out.println("This is test1");
Assert.assertNotNull(object);
}
@Test(dependsOnMethods={“test1"})
public void test2() {
System.out.println("This is test2");
}
@Test
public void test3() {
System.out.println("This is test3");
}
}
8/13/2013 techniqpatch.blogspot.com 47
JUnit vs. TestNG
8/13/2013 techniqpatch.blogspot.com 48
References
 http://en.wikipedia.org/wiki/TestNG
 http://www.mkyong.com/tutorials/testng-tutorials/
 http://testng.org/
 www.tutorialspoint.com
8/13/2013 techniqpatch.blogspot.com 49
Thank YOU
8/13/2013 techniqpatch.blogspot.com 50

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKEAbhishek 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
 
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
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
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
 
TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaEdureka!
 

Was ist angesagt? (20)

TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
testng
testngtestng
testng
 
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 with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
TestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKETestNG Session presented in Xebia XKE
TestNG Session presented in Xebia XKE
 
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
 
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
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
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
 
Unit test
Unit testUnit test
Unit test
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | Edureka
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Junit
JunitJunit
Junit
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 

Andere mochten auch

Introduction Priority Poker for Tester (Englisch)
Introduction Priority Poker for Tester (Englisch)Introduction Priority Poker for Tester (Englisch)
Introduction Priority Poker for Tester (Englisch)SwissQ Consulting AG
 
Selenium Basics Tutorial
Selenium Basics TutorialSelenium Basics Tutorial
Selenium Basics TutorialClever Moe
 
Automation Testing using Selenium
Automation Testing using SeleniumAutomation Testing using Selenium
Automation Testing using SeleniumNaresh Chintalcheru
 

Andere mochten auch (6)

Introduction Priority Poker for Tester (Englisch)
Introduction Priority Poker for Tester (Englisch)Introduction Priority Poker for Tester (Englisch)
Introduction Priority Poker for Tester (Englisch)
 
Selenium Basics Tutorial
Selenium Basics TutorialSelenium Basics Tutorial
Selenium Basics Tutorial
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 
Automation Testing using Selenium
Automation Testing using SeleniumAutomation Testing using Selenium
Automation Testing using Selenium
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 

Ähnlich wie Junit4&testng presentation

Ähnlich wie Junit4&testng presentation (20)

J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
05 junit
05 junit05 junit
05 junit
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
3 j unit
3 j unit3 j unit
3 j unit
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Junit
JunitJunit
Junit
 
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 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Junit
JunitJunit
Junit
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013
 
Unit testing by Svetlin Nakov
Unit testing by Svetlin NakovUnit testing by Svetlin Nakov
Unit testing by Svetlin Nakov
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Security Testing
Security TestingSecurity Testing
Security Testing
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 

Kürzlich hochgeladen

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Junit4&testng presentation

  • 1. By Sanjib Dhar 8/13/2013 techniqpatch.blogspot.com 1
  • 2. Why & What is Unit Testing  Testing is the process of checking the functionality of the application whether it is working as per requirements and to ensure that at developer level, unit testing comes into picture. Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.  It ensures the delivery of right product with right functionality. 8/13/2013 techniqpatch.blogspot.com 2
  • 3. What is JUnit ?  JUnit is a Regression Testing Framework* for the Java Programming Language. It is important in the test driven development, and is one of a family of unit testing frameworks collectively known as xUnit. *One of the main reasons for regression testing is to determine whether a change in one part of the software affects other parts of the software 8/13/2013 techniqpatch.blogspot.com 3
  • 4. How it works !!!  The idea is first testing then coding.  Test a little , code a little, test a little, code a little ,…… 8/13/2013 techniqpatch.blogspot.com 4
  • 5. Features  JUnit is an open source framework  Provides Annotation to identify the test methods.  Provides Assertions for testing expected results.  Provides Test runners for running tests.  Simple and easy to write. 8/13/2013 techniqpatch.blogspot.com 5
  • 6. What is Test case ??  A test case in software engineering is a set of conditions or variables under which a tester will determine whether an application or software system is working properly or not.  A test case definition include the following information :  pre-conditions  Set of input values  Set of expected results  How to execute the test and check results  Expected post-conditions. 8/13/2013 techniqpatch.blogspot.com 6
  • 7. Test case in JUnit !!!  A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected.  A formal written unit test case is characterized by a known input and by an expected output.  There must be at least two unit test cases for each requirement: one positive test and one negative test. 8/13/2013 techniqpatch.blogspot.com 7
  • 8. JUnit - Environment Setup  First setup jdk.  Set the environment variable JUNIT_HOME to C:JUNIT .  Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%junit4.10.jar;.;  If you are using Eclipse , install the plug-in for JUnit. 8/13/2013 techniqpatch.blogspot.com 8
  • 9. Component of JUnit  JUnit test framework provides following important features/component Fixtures Test suites Test runners JUnit classes 8/13/2013 techniqpatch.blogspot.com 9
  • 10. Fixtures  Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes setUp() method which runs before every test invocation. tearDown() method which runs after every test method. 8/13/2013 techniqpatch.blogspot.com 10
  • 11. Fixture Example import junit.framework.*; public class JavaTest extends TestCase { protected int value1, value2; // assigning the values protected void setUp(){ value1=2; value2=3; } // test method to add two values @Test public void testAdd(){ double result= value1 + value2; assertTrue(result == 5); } protected void tearDown () { //release resource } } 8/13/2013 techniqpatch.blogspot.com 11
  • 12. Test Suite  Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. 8/13/2013 techniqpatch.blogspot.com 12
  • 13. Test Suite Example Suite test class Classes to be tested import org.junit.runner.RunWi th; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class, TestJun it2.class }) public class JunitTestSuite { } import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { String message = "Robert"; @Test public void testPrintMessage() { assertEquals(message,”hii”); } } //create another class as TestJunit2 8/13/2013 techniqpatch.blogspot.com 13
  • 14. Test Runner  Test runner is used for executing the test cases.  Uses runClasses method of JUnitCore class of JUnit to run test case of created test class.  Gets the result of test cases run in Result Object.  Gets failure(s) using getFailures() methods of Result object.  Gets Success result using wasSuccessful() methods of Result object. 8/13/2013 techniqpatch.blogspot.com 14
  • 15. Example of Test Runner import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } 8/13/2013 techniqpatch.blogspot.com 15
  • 16. JUnit API’s  Assert  TestCase  TestResult  TestSuite 8/13/2013 techniqpatch.blogspot.com 16
  • 17. Assert public class Assert extends java.lang.Object This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are:  void assertEquals(boolean expected, boolean actual)  void assertFalse(boolean condition)  void assertNotNull(Object object)  void assertNull(Object object)  void assertTrue(boolean condition)  void fail()  void assertSame(boolean condition)  void assertNotSame(boolean condition) 8/13/2013 techniqpatch.blogspot.com 17
  • 18. Assert Example import org.junit.Test; import static org.junit.Assert.*; public class TestAssertions { @Test public void testAssertions() { //test data String str1 = new String (“sanjib"); String str2 = new String (“sanjib"); String str3 = null; String str4 = "abc"; String str5 = "abc"; int val1 = 5; int val2 = 6; String[] expectedArray = {"one", "two", "three"}; String[] resultArray = {"one", "two", "three"}; //Check that two objects are equal assertEquals(str1, str2); //Check that a condition is true assertTrue (val1 < val2); //Check that a condition is false assertFalse(val1 > val2); //Check that an object isn't null assertNotNull(str1); //Check that an object is null assertNull(str3); //Check if two object references point to the same object assertSame(str4,str5); //Check if two object references not point to the same object assertNotSame(str1,str3); //Check whether two arrays are equal to each other. assertArrayEquals(expectedArray, resultArray); } } 8/13/2013 techniqpatch.blogspot.com 18
  • 19. TestCase Class public abstract class TestCase extends Assert implements Test A test case defines the fixture to run multiple tests.Some important method of this class are:  int countTestCases() //Counts the number of test cases  TestResult createResult()//Creates a default TestResult object.  String getName() //Gets the name of a TestCase.  TestResult run() //method to run thetest.  void run(TestResult result) //Runs the test case and collects the results in TestResult.  void setName(String name)  void setUp()//e.g. open a network connection.  void tearDown() //e.g. close a network connection 8/13/2013 techniqpatch.blogspot.com 19
  • 20. TestCase Example package tv.seachange.ism.utils; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; public class TestCaseClass extends TestCase { protected double val1,val2; @Before public void setUp() { val1= 2.0; val2= 3.0; } @Test public void testAdd() { System.out.println("No of Test Case = "+ this.countTestCases()); //count the number of test cases String name= this.getName(); //test getName System.out.println("Test Case Name = "+ name); this.setName("newName"); //test setName String newName= this.getName(); System.out.println("Updated Test Case Name = "+ newName); assertFalse(val1>val2); } public void tearDown( ) {//tearDown used to close the connection or clean up activities } } 8/13/2013 techniqpatch.blogspot.com 20
  • 21. Test Result  A TestResult collects the results of executing a test case.Some of its methods are:  void addError(Test test, Throwable t)//Adds an error to the list of errors.  void addFailure(Test test, AssertionFailedError t)//Adds a failure to the list of failures.  int errorCount()//Gets the number of detected errors.  int failureCount()//Gets the number of detected failures.  void run(TestCase test)//Runs a TestCase.  void stop()//Marks that the test run should stop. 8/13/2013 techniqpatch.blogspot.com 21
  • 22. TestSuite Class  A TestSuite is a Composite of Tests. It runs a collection of test cases. Some of the methods are  void addTest(Test test)//Adds a test to the suite.  int countTestCases()//Counts the number of test cases that will be run by this test.  String getName()//Returns the name of the suite.  void setName(String name)//Sets the name of the suite.  Test testAt(int index)//Returns the test at the given index. 8/13/2013 techniqpatch.blogspot.com 22
  • 23. TestSuite Example import junit.framework.*; public class TestSuiteTest { public static void main(String[] a) { // add the test's in the suite TestSuite suite = new TestSuite(JunitTest1.class, JunitTest2.class, JunitTest3.class ); TestResult result = new TestResult(); suite.run(result); System.out.println("Number of test cases = " + result.runCount()); } } 8/13/2013 techniqpatch.blogspot.com 23
  • 24. Execution Flow  First of all beforeClass() method execute only once  Lastly, the afterClass() method executes only once.  before() method executes for each test case but before executing the test case.  after() method executes for each test case but after the execution of test case  In between before() and after() each test case executes. 8/13/2013 techniqpatch.blogspot.com 24
  • 25. Execution Flow Example import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class JunitExecutionFlow { //execute only once, in the starting @BeforeClass public static void beforeClass() { System.out.println("in before class"); } //execute only once, in the end @AfterClass public static void afterClass() { System.out.println("in after class"); } //execute for each test, before executing test @Before public void before() { System.out.println("in before"); } //execute for each test, after executing test @After public void after() { System.out.println("in after"); } //test case 1 @Test public void testCase1() { System.out.println("in test case 1"); } //test case 2 @Test public void testCase2() { System.out.println("in test case 2"); } } 8/13/2013 techniqpatch.blogspot.com 25
  • 26. Ignore Test  Sometimes it happens that our code is not ready and test case written to test that method/code will fail if run or we just don’t want to test that test case at that moment. The @Ignore annotation helps in this regards. A test method annotated with @Ignore will not be executed. If a test class is annotated with @Ignore then all of its test methods will be ignored. 8/13/2013 techniqpatch.blogspot.com 26
  • 27. Ignored Test Example import org.junit.Ignore; import org.junit.Test; @Ignore public class IgnoreTest { @Test public void notIgnored() { System.out.println("this is executed"); } @Ignore @Test public void itIsIgnored() { System.out.println("This test is ignored"); } } 8/13/2013 techniqpatch.blogspot.com 27
  • 28. Time test Junit provides a handy option of Timeout. If a test case takes more time than specified number of milliseconds then Junit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. 8/13/2013 techniqpatch.blogspot.com 28
  • 29. Time Test xample import org.junit.Test; public class TimeTest { @Test(timeout=10) public void testTime() { for(int i=0;i<1000;i++){ System.out.println("hiiiiii"); } } } 8/13/2013 techniqpatch.blogspot.com 29
  • 30. Exception Test  Junit provides a option of tracing the Exception handling of code. You can test the code whether code throws desired exception or not. The expected parameter is used along with @Test annotation. 8/13/2013 techniqpatch.blogspot.com 30
  • 31. Exception Test Example import org.junit.Test; public class ExceptionTest { @Test(expected=ArithmeticException.class) public void exception() { int s=12/0; } } 8/13/2013 techniqpatch.blogspot.com 31
  • 32. Parameterized Test  Junit 4 has introduced a new feature Parameterized tests.Parameterized tests allow developer to run the same test over and over again using different values. There are five steps, that you need to follow to create Parameterized tests.  Annotate test class with @RunWith(Parameterized.class)  Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.  Create a public constructor that takes in what is equivalent to one "row" of test data.  Create an instance variable for each "column" of test data.  Create your tests case(s) using the instance variables as the source of the test data. 8/13/2013 techniqpatch.blogspot.com 32
  • 33. Parameterized Test Example @RunWith(Parameterized.class) public class ParameterizedTest { private Integer inputNumber; private Boolean expectedResult; private OddEvenChecker oddEvenChecker; @Before public void initialize() { oddEvenChecker = new OddEvenChecker(); } public ParameterizedTest(Integer inputNumber, Boolean expectedResult) { this.inputNumber = inputNumber; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection checkNumbers() { return Arrays.asList(new Object[][] { { 2, true },{ 6, true },{ 19, false },{ 22, true },{ 23, false } }); } @Test public void testOddEvenChecker() { System.out.println("Parameterized Number is : " + inputNumber); assertEquals(expectedResult, oddEvenChecker.checkNumber(inputNumber)); } } 8/13/2013 techniqpatch.blogspot.com 33
  • 34. Are we done ??  Wow !! Now we know about Junit .But still some question is there : What if we want to test the dependency ? Or What if we want to use Object as parameter not only primitives ?? 8/13/2013 techniqpatch.blogspot.com 34
  • 35. Yes we can !!  And the solution is TESTNG 8/13/2013 techniqpatch.blogspot.com 35
  • 36. TestNG  It stands for NEXT GENERATION JAVA TESTING.  TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities in order to make it more powerful and easier to use. 8/13/2013 techniqpatch.blogspot.com 36
  • 37. Features of TestNG  Annotations.  Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc...).  Flexible test configuration.  Support for data-driven testing (with @DataProvider).  Support for parameters.  Powerful execution model (no more TestSuite).  Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc...).  Dependent methods for application server testing. 8/13/2013 techniqpatch.blogspot.com 37
  • 38. Annotations import java.util.*; import org.testng.Assert; import org.testng.annotations.*; public class TestNGTest1 { private Collection collection; @BeforeClass public void oneTimeSetUp() { // one-time initialization code System.out.println("@BeforeClass - oneTimeSetUp"); } @AfterClass public void oneTimeTearDown() { // one-time cleanup code System.out.println("@AfterClass - oneTimeTearDown"); } @BeforeMethod public void setUp() { collection = new ArrayList(); System.out.println("@BeforeMethod - setUp"); } @AfterMethod public void tearDown() { collection.clear(); System.out.println("@AfterMethod - tearDown"); } @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"); } } The annotations are : @BeforeClass @AfterClass @BeforeMethod @AfterMethod @Test @BeforeTest @AfterTest etc.. 8/13/2013 techniqpatch.blogspot.com 38
  • 39. Expected Exception Test import org.testng.annotations.*; public class TestNGTest2 { @Test(expectedExceptions = ArithmeticException.class) public void divisionWithException() { int i = 1/0; } } 8/13/2013 techniqpatch.blogspot.com 39
  • 40. Ignore and Time test  In TestNG for ignoring a test below mention annotation is used : @Test(enabled=false)  For Time test the annotation is same as Junit. @Test(timeOut = 1000) 8/13/2013 techniqpatch.blogspot.com 40
  • 41. Suite or Grouping  The grouping is used for running multiple test as a group of tests. Unlike JUnit in TestNG we can make different group of test method and can run single or multiple group. 8/13/2013 techniqpatch.blogspot.com 41
  • 42. Suite or Grouping Test public class GroupingTest { @Test(groups="group1") public void testingGroup1 () { System.out.println("Method - testingMethod1()"); } @Test(groups="group2") public void testingGroup2 () { System.out.println("Method - testingMethod2()"); } @Test(groups="group1") public void testingGroup1_1 () { System.out.println("Method - testingMethod1_1()"); } @Test(groups="group3") public void testingGroup4() { System.out.println("Method - testingMethod4()"); } } 8/13/2013 techniqpatch.blogspot.com 42 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name="My suite"> <test name="testinggroup"> <groups> <run> <include name="group1"/> </run> </groups> <classes> <class name="GroupingTest" /> </classes> </test> </suite>
  • 43. TestNG’s Parameterized Test  TestNG’s Parameterized test is very user friendly and flexible (either in XML file or inside the class). It can support many complex data type as parameter value and the possibility is unlimited. Moreover we even can pass in our own object for Parameterized test. 8/13/2013 techniqpatch.blogspot.com 43
  • 44. TestNG Parameterized Example public class ParameterizedTest { @Test(dataProvider = "parameterizedDataProvider") public void testParameter(User user,boolean flag) { System.out.println("the user name is :"+user.getName()); System.out.println("the user id is :"+user.getId()); } @DataProvider(name="parameterizedDataProvi der") public Object[][] parameterizedDataProvider() { return new Object[][] { {new User("Sanjib",1),true}, {new User("Dhar",2),false} }; } } class User{ private String name; private int id; public User() { } public User(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } 8/13/2013 techniqpatch.blogspot.com 44
  • 45. Dependency Test  The TestNG has a feature called The “Dependency Test”, means methods are tested base on dependency. If the dependent method fails, all the subsequent test methods will be skipped, not marked as failed. 8/13/2013 techniqpatch.blogspot.com 45
  • 46. @DataProvider  A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, theData Provider’s name automatically defaults to the method’s name.  A Data Provider returns Java objects that will be passed as parameters to an @Test method. The name of the Data Provider to receive parameters from is specified in the dataProvider attribute of the @Test annotation. 8/13/2013 techniqpatch.blogspot.com 46
  • 47. Dependency Test example public class DependencyTest { @Test public void test1() { Object object = null; System.out.println("This is test1"); Assert.assertNotNull(object); } @Test(dependsOnMethods={“test1"}) public void test2() { System.out.println("This is test2"); } @Test public void test3() { System.out.println("This is test3"); } } 8/13/2013 techniqpatch.blogspot.com 47
  • 48. JUnit vs. TestNG 8/13/2013 techniqpatch.blogspot.com 48
  • 49. References  http://en.wikipedia.org/wiki/TestNG  http://www.mkyong.com/tutorials/testng-tutorials/  http://testng.org/  www.tutorialspoint.com 8/13/2013 techniqpatch.blogspot.com 49