JUnit - Tutorialspoint

2y ago
258 Views
15 Downloads
750.18 KB
24 Pages
Last View : 22d ago
Last Download : 2m ago
Upload by : Laura Ramon
Transcription

JUnitAbout the TutorialJUnit is a unit testing framework for Java programming language. JUnit has beenimportant in the development of test-driven development, and is one of a familyof unit testing frameworks collectively known as xUnit, that originated with JUnit.This tutorial explains the use of JUnit in your project unit testing, while workingwith Java. After completing this tutorial you will gain sufficient knowledge in usingJUnit testing framework from where you can take yourself to next levels.AudienceThis tutorial has been prepared for beginners to help them understand the basicfunctionality of JUnit tool.PrerequisitesWe assume you are going to use JUnit to handle all levels of Java projectsdevelopment. So it will be good if you have the knowledge of softwaredevelopment using any programming language, especially Java programming andsoftware testing process.Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of TutorialsPoint (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,distribute or republish any contents or a part of contents of this e-book in anymanner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and asprecisely as possible, however, the contents may contain inaccuracies or errors.Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,timeliness or completeness of our website or its contents including this tutorial. Ifyou discover any errors on our website or in this tutorial, please notify us atcontact@tutorialspoint.comTable of ContentsAbout the Tutorial . ii

JUnitAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents . ii1. OVERVIEW . 1What is JUnit? . 1Features of JUnit . 2What is a Unit Test Case? . 22. ENVIORNMENT SETUP . 3Try it Online Option . 3Local Environment Setup . 33. TEST FRAMEWORK . 8Features of Junit Test Framework . 84. BASIC USAGE. 12Create a Class . 12Create Test Case Class . 12Create Test Runner Class. 135. API . 16Assert Class . 16TestCase Class . 18TestResult Class . 21TestSuite Class . 246. WRITING A TEST . 277. USING ASSERTION . 32Assertion. 32ii

JUnitAnnotation. 358. EXECUTION PROCEDURE . 399. EXECUTING TESTS . 42Create a Class . 42Create Test Case Class . 43Create Test Runner Class . 4310. SUITE TEST . 45Create a Class . 45Create Test Case Classes . 46Create Test Suite Class . 47Create Test Runner Class . 4711. IGNORE A TEST . 49Create a Class . 49Create Test Case Class . 50Create Test Runner Class . 5112. TIME TEST . 54Create a Class . 54Create Test Case Class . 55Create Test Runner Class. 5613. EXCEPTIONS TEST. 57Create a Class . 57Create Test Case Class . 58Create Test Runner Class . 5914. PARAMETERIZED TEST. 60Create a Class . 60iii

JUnitCreate Parameterized Test Case Class . 61Create Test Runner Class . 6215. PLUG WITH ANT . 64Step 1: Download Apache Ant . 64Step 2: Set Ant Environment . 64Step 3: Download JUnit Archive . 65Step 4: Create Project Structure . 65Create ANT Build.xml . 6716. PLUG WITH ECLIPSE . 71Step 1: Download JUnit Archive . 71Step 2: Set Eclipse Environment . 71Step 3: Verify Junit installation in Eclipse . 7217. EXTENSIONS . 77Cactus . 77JWebUnit . 78XMLUnit . 79MockObject . 80iv

1. OVERVIEWJUnitTesting is the process of checking the functionality of an application to ensure it runsas per requirements. Unit testing comes into picture at the developers’ level; it is thetesting of single entity (class or method). Unit testing plays a critical role in helpinga software company deliver quality products to its customers.Unit testing can be done in two ways: manual testing and automated testing.Manual TestingAutomated TestingExecuting a test cases manuallywithout any tool support is knownas manual testing.Taking tool support and executing thetest cases by using an automation toolis known as automation testing.Time-consuming and tedious:Since test cases are executed byhuman resources, it is very slowand tedious.Fast: Automation runs test casessignificantly faster than humanresources.Huge investment in humanresources: As test cases need tobe executed manually, more testersare required in manual testing.Less investment in humanresources: Test cases are executedusing automation tools, so less numberof testers are required in automationtesting.Less reliable: Manual testing isless reliable, as it has to accountfor human errors.More reliable: Automation tests areprecise and reliable.Non-programmable: Noprogramming can be done to writesophisticated tests to fetch hiddeninformation.Programmable: Testers can programsophisticated tests to bring out hiddeninformation.5

JUnitWhat is JUnit?JUnit is a unit testing framework for Java programming language. It plays a crucialrole test-driven development, and is a family of unit testing frameworks collectivelyknown as xUnit.JUnit promotes the idea of "first testing then coding", which emphasizes on settingup the test data for a piece of code that can be tested first and then implemented.This approach is like "test a little, code a little, test a little, code a little." It increasesthe productivity of the programmer and the stability of program code, which in turnreduces the stress on the programmer and the time spent on debugging.Features of JUnit JUnit is an open source framework, which is used for writing and running tests. Provides annotations to identify test methods. Provides assertions for testing expected results. Provides test runners for running tests. JUnit tests allow you to write codes faster, which increases quality. JUnit is elegantly simple. It is less complex and takes less time. JUnit tests can be run automatically and they check their own results andprovide immediate feedback. There's no need to manually comb through areport of test results. JUnit tests can be organized into test suites containing test cases and evenother test suites. JUnit shows test progress in a bar that is green if the test is running smoothly,and it turns red when a test fails.What is a Unit Test Case?A Unit Test Case is a part of code, which ensures that another part of code (method)works as expected. To achieve the desired results quickly, a test framework isrequired. JUnit is a perfect unit test framework for Java programming language.A formal written unit test case is characterized by a known input and an expectedoutput, which is worked out before the test is executed. The known input should testa precondition and the expected output should test a post-condition.6

JUnitThere must be at least two unit test cases for each requirement: one positive testand one negative test. If a requirement has sub-requirements, each sub-requirementmust have at least two test cases as positive and negative.7

2. ENVIRONMENT SETUPJUnitTry it Online OptionWe already have set up Java programming environment online, so that you cancompile and execute all the available examples online at the same time while you aredoing your theory work. It gives you confidence in what you are reading and verifythe programs with different options. Feel free to modify any example and execute itonline.Try the following example er optionavailableatpublic class MyFirstJavaProgram {public static void main(String []args) {System.out.println("Hello World");}}For most of the examples given in this tutorial, you will find a Try it option in ourwebsite code sections at the top right corner that will take you to the online compiler.So just make use of it and enjoy your learning.Local Environment SetupJUnit is a framework for Java, so the very first requirement is to have JDK installedin your machine.System RequirementJDK1.5 or above.MemoryNo minimum requirement.8

JUnitDisk SpaceNo minimum requirement.Operating SystemNo minimum requirement.Step 1: Verify Java Installation in Your MachineFirst of all, open the console and execute a java command based on the operatingsystem you are working on.OSTaskCommandWindowsOpen Command Consolec:\ java -versionLinuxOpen Command Terminal java -versionMacOpen Terminalmachine: joseph java -versionLet's verify the output for all the operating systems:OSWindowsOutputjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode,sharing)Linuxjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)9

JUnitJava HotSpot(TM) Client VM (build 17.0-b17, mixed mode,sharing)Macjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixedmode, sharing)If you do not have Java installed on your system, then download the Java SoftwareDevelopment Kit (SDK) from the following /downloads/index.htmlWe are assuming Java 1.6.0 21 as the installed version for this tutorial.Step 2: Set JAVA EnvironmentSet the JAVA HOME environment variable to point to the base directory locationwhere Java is installed on your machine. For example,OSOutputWindowsSet the environment variable JAVA HOME to C:\ProgramFiles\Java\jdk1.6.0 21Linuxexport JAVA HOME /usr/local/java-currentMacexport JAVA HOME /Library/Java/HomeAppend Java compiler location to the System Path.OSOutput10

JUnitWindowsAppend the string C:\ProgramFiles\Java\jdk1.6.0 21\bin at the end of the systemvariable, Path.Linuxexport PATH PATH: JAVA HOME/bin/Macnot requiredVerify Java installation using the command java -version as explained above.Step 3: Download Junit ArchiveDownload the latest version of JUnit jar file from http://www.junit.org. At the time ofwriting this tutorial, we have downloaded Junit-4.10.jar and copied it into C:\ JUnitfolder.OSArchive 4.10.jarStep 4: Set JUnit EnvironmentSet the JUNIT HOME environment variable to point to the base directory locationwhere JUNIT jar is stored on your machine. Let’s assuming we've stored junit4.10.jarin the JUNIT folder.OSWindowsDescriptionSet the environment variable JUNIT HOME to C:\JUNIT11

JUnitLinuxexport JUNIT HOME /usr/local/JUNITMacexport JUNIT HOME /Library/JUNITStep 5: Set CLASSPATH VariableSet the CLASSPATH environment variable to point to the JUNIT jar location.OSDescriptionWindowsSet the environment variable CLASSPATH to%CLASSPATH%;%JUNIT HOME%\junit4.10.jar;.;LinuxexportCLASSPATH CLASSPATH: JUNIT HOME/junit4.10.jar:.MacexportCLASSPATH CLASSPATH: JUNIT HOME/junit4.10.jar:.Step 6: Test JUnit SetupCreate a java class file name TestJunit in C:\ JUNIT WORKSPACEimport org.junit.Test;import static org.junit.Assert.assertEquals;public class TestJunit {@Testpublic void testAdd() {String str "Junit is working fine";assertEquals("Junit is working fine",str);}}12

JUnitCreate a java class file name TestRunner in C:\ JUNIT WORKSPACE to executetest case(s).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()) t.println(result.wasSuccessful());}}Step 7: Verify the ResultCompile the classes using javac compiler as follows:C:\JUNIT WORKSPACE javac TestJunit.java TestRunner.javaNow run the Test Runner to see the result as follows:C:\JUNIT WORKSPACE java TestRunnerVerify the output.tr

JUnit is an open source framework, which is used for writing and running tests. Provides annotations to identify test methods. Provides assertions for testing expected results. Provides test runners for running tests. JUnit tests allow you to write codes faster, which incre

Related Documents:

line and build plugins for Gradle and Maven as well as a JUnit 4 based Runner for running any TestEngine on the platform. JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. The Jupiter sub-project provides a TestEngine for running Jupiter based tests on the platform.

Agenda JUnit & Coroutines: Problems JUnit 5: Platform, Jupiter, etc JUnit & Coroutines: Solutions Testing Coroutines

NFP121 5 Sommaire 1) Tests et tests unitaires - Outil : junit www.junit.org une présentation Tests d'une application - Une pile et son IHM Tests unitaires de la pile Tests de plusieurs implémentations de piles Tests d'une IHM Tests de sources java Invariant et fonction d'abstraction comme tests - Tests en boîte noire - Tests en boîte blanche

tutorialspoint.com or google.com these are domain names. A domain name has two parts, TLD (Top Level Domain) and SLD (Second level domain), for example in tutorialspoint.com, tutorialspoint is second level domain of TLD .com, or you can say it's a subdomain of .com TLD. There are many top level domains available, like .com,

JUnit: A framework for designing and testing Java types using classes Can be used standalone, but is part of all Java Development Environments: Eclipse, Dr. Java, BlueJ, NetBeans, . . . Virtually all programming languages have a similar testing tool: C Unit, PyUnit, HTTPU

JSF Apache Struts EJBs Toplink Ant, JUnit CVS Oracle S9iAS Profiling Audit/Metrics JSP Struts UI Project Toplink Model Project T e c h n o l o g y c o p e s Visual & Declarative UML Swing, HTML JSP JSF Apache Struts ADF Controller ADF BC EJBs Toplink Ant, JUnit CVS Clearcase Oracle SCM Oracle 9iAS JBoss, WLS Profiling Audit/Metrics E x t e n s .

JUnit Tutorial 3 / 26 common way of usage. Of course, if a method is very complex and extended, we can have more than one test methods for this complex method. The details of creating test cases will be presented in the next sections. Below, there is the code of the class named CalculateTest.java, which has the role of our test class .

American Revolution Wax Museum Project Overview You will become an expert on one historical figure who played a significant role in the American Revolution. For this individual, you complete the following tasks: 1. Notes: Use at least 3 sources to research and take notes about the individualʼs life, views, and impact. At least one of