Author: Sascha Wolski Sebastian Hennebrueder http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet and eclipse.



Similar documents
Unit Testing and JUnit

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

JUnit. Introduction to Unit Testing in Java

Using JUnit in SAP NetWeaver Developer Studio

+ Introduction to JUnit. IT323 Software Engineering II By: Mashael Al-Duwais

This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application.

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

JUnit Automated Software Testing Framework. Jeff Offutt. SWE 437 George Mason University Thanks in part to Aynur Abdurazik. What is JUnit?

Unit Testing. and. JUnit

Approach of Unit testing with the help of JUnit

TESTING WITH JUNIT. Lab 3 : Testing

Effective unit testing with JUnit

JUnit Howto. Blaine Simpson

How to Write AllSeen Alliance Self- Certification Test Cases September 25, 2014

Table of Contents. LESSON: The JUnit Test Tool...1. Subjects...2. Testing What JUnit Provides...4. JUnit Concepts...5

UNIT TESTING. Written by Patrick Kua Oracle Australian Development Centre Oracle Corporation

Unit Testing with JUnit and CppUnit

Java. Java. e=mc 2. composition

Using Testing and JUnit Across The Curriculum

Java Server Pages combined with servlets in action. Generals. Java Servlets

Agile/Automated Testing

JUnit - A Whole Lot of Testing Going On

Java Programming Language

Unit-testing with JML

A Practical Guide to Test Case Types in Java

Unit Testing JUnit and Clover

Testing, Debugging, and Verification

Unit testing with JUnit and CPPUnit. Krzysztof Pietroszek

CS 111 Classes I 1. Software Organization View to this point:

OTN Developer Day Enterprise Java. Hands on Lab Manual JPA 2.0 and Object Relational Mapping Basics

Test Driven Development

AP Computer Science Java Subset

Tutorial IV: Unit Test

Capabilities of a Java Test Execution Framework by Erick Griffin

How To Test In Bluej

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Java course - IAG0040. Unit testing & Agile Software Development

Unit Testing & JUnit

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Tools for Integration Testing

Going Interactive: Combining Ad-Hoc and Regression Testing

Tutorial for Spring DAO with JDBC

Web Service Caching Using Command Cache

Java Interview Questions and Answers

ID TECH UniMag Android SDK User Manual

Java Unit testing with JUnit 4.x in Eclipse

Project 4 DB A Simple database program

tools that make every developer a quality expert

Tutorial 7 Unit Test and Web service deployment

OVERVIEW OF TESTING FIRST

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

IBM Tivoli Workload Scheduler Integration Workbench V8.6.: How to customize your automation environment by creating a custom Job Type plug-in

Introduction to unit testing with Java, Eclipse and Subversion

Testing Tools and Techniques

Integrating Educational Technology into Teaching (4 th Edition) Adobe Acrobat Tutorial for Chapter 15 TIE-into Practice Exercises

Creating a 2D Game Engine for Android OS. Introduction

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Orders.java. ArrayList of Drinks as they are ordered. Functions to calculate statistics on Drinks

Chapter 1: Web Services Testing and soapui

Data Crow Creating Reports

Building a test harness is. an effort that often takes. on a life of its own. But it. doesn t have to get wildly out of control.

Performance Testing from User Perspective through Front End Software Testing Conference, 2013

Jemmy tutorial. Introduction to Jemmy testing framework. Pawel Prokop. March 14,

Agile.NET Development Test-driven Development using NUnit

Plugin JUnit. Contents. Mikaël Marche. November 18, 2005

16.1 DataFlavor DataFlavor Methods. Variables

NICK COLLIER - REPAST DEVELOPMENT TEAM

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

How to set up a database in Microsoft Access

Unit Testing with zunit

Software Construction

CSE 308. Coding Conventions. Reference

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

SpiraTest / SpiraTeam Automated Unit Testing Integration & User Guide Inflectra Corporation

Creating Java EE Applications and Servlets with IntelliJ IDEA

Building Web Services with Apache Axis2

Android Developer Fundamental 1

Automate APIs with Groovy Script

Advantages. manage port forwarding, set breakpoints, and view thread and process information directly

How to Attach the Syllabus and Course Schedule to a Content Item

10 Java API, Exceptions, and Collections

Android Environment SDK

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

e-builder Online User Assistance esignature Setup Guide

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

Visual Basic Programming. An Introduction

We are not repeating all the basics here. Have a look at the basic EJB tutorials before you start this tutorial.

Introduction to Microsoft Access 2003

Unit Testing with FlexUnit. by John Mason

Tutorial for Creating Resources in Java - Client

SpotWeb: Detecting Framework Hotspots and Coldspots via Mining Open Source Code on the Web

Wicket Application Development

How to develop your own app

Accessing the Online Meeting Room (Blackboard Collaborate)

HP Operations Orchestration Software

Hands-On Lab. Client Workflow. Lab version: Last updated: 2/23/2011

Creating A Walking Skeleton

D06 PROGRAMMING with JAVA

Primavera P6 Professional Windows 8 Installation Instructions. Primavera P6. Installation Instructions. For Windows 8 Users

Struts Tools Tutorial. Version: M5

Transcription:

JUnit Testing JUnit is a simple Java testing framework to write tests for you Java application. This tutorial gives you an overview of the features of JUnit and shows a little example how you can write tests for your Java application. General Author: Sascha Wolski Sebastian Hennebrueder http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet and eclipse. Date: April, 12 2005 Software: Eclipse 3.x Junit 2.x Source code: http://www.laliluna.de/assets/tutorials/junit-testing-source.zip PDF Version http://www.laliluna.de/assets/tutorials/junit-testing-en.pdf What is JUnit JUnit is a simple open source Java testing framework used to write and run repeatable automated tests. It is an instance of the xunit architecture for unit testing framework. Eclipse supports creating test cases and running test suites, so it is easy to use for your Java applications. JUnit features include: Assertions for testing expected results Test fixtures for sharing common test data Test suites for easily organizing and running tests Graphical and textual test runners What is a test case A test case is a class which holds a number of test methods. For example if you want to test some methods of a class Book you create a class BookTest which extends the JUnit TestCase class and place your test methods in there. How you write and run a simple test 1. Create a subclass of TestCase: public class BookTest extends TestCase{ //.. 2. Write a test method to assert expected results on the object under test: Note: The naming convention for a test method is testxxx() public void testcollection() { Collection collection = new ArrayList(); asserttrue(collection.isempty());

3. Write a suite() method that uses reflection to dynamically create a test suite containing all the testxxx() methods: public static Test suite(){ return new TestSuite(BookTest.class); 4. Activate the JUnit view in Eclipse (Window > Show View > Other.. > Java > JUnit). You find the JUnit tab near the Package Explorer tab. You can change the position of the tab by drag and drop it.

5. Right click on the subclass of TestCase and choose Run > JUnit Test to run the test. Using a test fixture A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the test code necessary to initialize and cleanup those common objects for each test. To create a test fixture, define a setup() method that initializes common object and a teardown() method to cleanup those objects. The JUnit framework automatically invokes the setup() method before a each test is run and the teardown() method after each test is run. The following test uses a test fixture: public class BookTest2 extends TestCase { private Collection collection; protected void setup() { collection = new ArrayList(); protected void teardown() { collection.clear(); public void testemptycollection(){ asserttrue(collection.isempty()); Dynamic and static way of running single tests JUnit supports two ways (static and dynamic) of running single tests. In static way you override the runtest() method inherited form TestCase class and call the desired test case. A convenient way to do this is with an anonymous inner class. Note: Each test must be given a name, so you can identify it if it fails. TestCase test = new BookTest("equals test") { public void runtest() { testequals(); ; The dynamic way to create a test case to be run uses reflection to implement runtest. It assumes the name of the test is the name of the test case method to invoke. It dynamically finds and invokes the test method. The dynamic way is more compact to write but it is less static type safe. An error in the name of the test case goes unnoticed until you run it and get a NoSuchMethodException. We leave the choice of which to use up to you. TestCast test = new BookTest("testEquals"); What is a TestSuite If you have two tests and you'll run them together you could run the tests one at a time yourself, but you would quickly grow tired of that. Instead, JUnit provides an object TestSuite which runs any number of test cases together. The suite method is like a main method that is specialized to run tests. Create a suite and add each test case you want to execute: public static void suite(){ TestSuite suite = new TestSuite(); suite.addtest(new BookTest("testEquals")); suite.addtest(new BookTest("testBookAdd"));

return suite; Since JUnit 2.0 there is an even simpler way to create a test suite, which holds all testxxx() methods. You only pass the class with the tests to a TestSuite and it extracts the test methods automatically. Note: If you use this way to create a TestSuite all test methods will be added. If you do not want all test methods in the TestSuite use the normal way to create it. Example: public static void suite(){ return new TestSuite(BookTest.class); A little example Create a new Java project named JUnitExample. Add a package de.laliluna.tutorial.junitexample where you place the example classes and a package test.laliluna.tutorial.junitexample where you place your test classes. The class Book Create a new class Book in the package de.laliluna.tutorial.junitexample. Add two properties title of type String and price of type double. Add a constructor to set the two properties. Provide a getter- and setter-method for each of them. Add a method trunk for a method equals(object object) which checks if the object is an instance of the class Book and the values of the object are equal. The method return a boolean value. Note: Do not write the logic of the equals(..) method, we do it after finish creating the test method. The following source code shows the class Book. public class Book { private String title; private double price; * Constructor * * @param title * @param price public Book(String title, double price) { this.title = title; this.price = price; * Check if an object is an instance of book * and the values of title and price are equal * then return true, otherwise return false public boolean equals(object object) { return false; public double getprice() { return price;

public void setprice(double price) { this.price = price; public String gettitle() { return title; public void settitle(string title) { this.title = title; The test case BookTest Create a new test case BookTest in the package test.laliluna.tutorial.junitexample Right click on the package and choose New > JUnit Test Case. In the wizard choose the methods stubs setup(), teardown() and constructor(). The following source code shows the class BookTest public class BookTest extends TestCase { * setup() method that initializes common objects protected void setup() throws Exception { super.setup(); * teardown() method that cleanup the common objects protected void teardown() throws Exception { super.teardown();

* Constructor for BookTest. * @param name public BookTest(String name) { super(name); Now we want to write a test for the equals(..) method of the class Book. We provide three private properties, book1, book2 and book3 of type Book. private Book book1; private Book book2; private Book book3; Within the setup() method we initializes the three properties with some values. Property book1 and book3 are the same. protected void setup() throws Exception { super.setup(); book1 = new Book("ES", 12.99); book2 = new Book("The Gate", 11.99); book3 = new Book("ES", 12.99); Within the teardown() method we cleanup the properties: protected void teardown() throws Exception { super.teardown(); book1 = null; book2 = null; book3 = null; Now, add a test method testequals() to the test case. Within the method we use the assertfalse() method of the JUnit framework to test if the return-value of the equals(..) method is false, because book1 and book2 are not the same. If the return-value is false the logic of the equals() method is correct, otherwise there is a logical problem while comparing the objects. We want to test if the method compares the objects correctly by using the asserttrue() method. Book1 and Book3 are the same, because both are an instance of the class Book and have the same values. The following source code shows the testequals() method: public void testequals(){ assertfalse(book2.equals(book1)); asserttrue(book1.equals(book1)); Writing the logic of the equals() method We have finished the test and now we can add the logic to the equals() method stub. Open the class Book and add the logic to the equals() method. First we check if the object given by the method is an instance of Book. Then compare the properties title and price, if they are equal return true. public boolean equals(object object) { if (object instanceof Book) { Book book = (Book) object; return gettitle().equals(book.gettitle()) && getprice() == book.getprice(); return false;

Create the suite() method In order to run the test method testequals() add a method suite() to the class BookTest. Note: You can also create a separate class where you add the suite() method. Within the method create a new instance of TestSuite and use the method addtest(..) to add a test. Here we use the dynamically way to add a test to a TestSuite. The method looks like the follows: public static Test suite(){ TestSuite suite = new TestSuite(); suite.addtest(new BookTest("testEquals")); return suite; Run the test After finishing all test methods we want to run the JUnit test case. Right mouse button on the class BookTest and choose Run As > JUnit Test. On the JUnit view (Menu Windows -> show view) of Eclipse you can see how many runs, errors and failures occurred.