Top Banner
By Sanjib Dhar 06/06/2022 techniqpatch.blogspot.com 1 JUnit 4 & TESTNG
50

Junit4&testng presentation

Nov 16, 2014

Download

Technology

Sanjib Dhar

This presentation describes the some of the major functionality of JUnit4 and TestNG .Each topic contains example so that a viewer can understand the usage and apply them in their code.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 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 APIs 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 dont 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