Unit Testing and JUnit



Similar documents
Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

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

Effective unit testing with JUnit

Approach of Unit testing with the help of JUnit

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

Unit Testing JUnit and Clover

JUnit - A Whole Lot of Testing Going On

Unit Testing. and. JUnit

JUnit. Introduction to Unit Testing in Java

TESTING WITH JUNIT. Lab 3 : Testing

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

Java Unit testing with JUnit 4.x in Eclipse

Unit-testing with JML

Unit Testing & JUnit

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

The junit Unit Tes(ng Tool for Java

CSE 326: Data Structures. Java Generics & JUnit. Section notes, 4/10/08 slides by Hal Perkins

Using JUnit in SAP NetWeaver Developer Studio

Test Driven Development

Writing Self-testing Java Classes with SelfTest

Java course - IAG0040. Unit testing & Agile Software Development

Tutorial for Spring DAO with JDBC

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

AP Computer Science Java Subset

Java Interview Questions and Answers

Test Driven Development

J a v a Quiz (Unit 3, Test 0 Practice)

Chapter 1: Web Services Testing and soapui

Going Interactive: Combining Ad-Hoc and Regression Testing

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Unit Testing with JUnit and CppUnit

Tools for Integration Testing

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

Capabilities of a Java Test Execution Framework by Erick Griffin

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

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

Tutorial 7 Unit Test and Web service deployment

Fundamentals of Java Programming

Agile.NET Development Test-driven Development using NUnit

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

How to Install Java onto your system

Unit testing with JUnit and CPPUnit. Krzysztof Pietroszek

Java Programming Language

Java Programming Fundamentals

Tutorial IV: Unit Test

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to C Unit Testing (CUnit) Brian Nielsen Arne Skou

Java Bluetooth stack Acceptance Test Plan Version 1.0

LAB4 Making Classes and Objects

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

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

Testing, Debugging, and Verification

An Overview of Java. overview-1

Introduction to unit testing with Java, Eclipse and Subversion

Part I. Multiple Choice Questions (2 points each):

Inheritance, overloading and overriding

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Java Software Development Kit (JDK 5.0 Update 14) Installation Step by Step Instructions

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Announcement. SOFT1902 Software Development Tools. Today s Lecture. Version Control. Multiple iterations. What is Version Control

How To Test In Bluej

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

A Practical Guide to Test Case Types in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

How to use the Eclipse IDE for Java Application Development

6.1. Example: A Tip Calculator 6-1

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Tutorial: Getting Started

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

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

Sample CSE8A midterm Multiple Choice (circle one)

Moving from CS 61A Scheme to CS 61B Java

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Software Engineering Techniques

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

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

Software Development with UML and Java 2 SDJ I2, Spring 2010

Continuous Integration Part 2

Appendix A Using the Java Compiler

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Testing Methodology Assignment 1 Unit testing using JUnit

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

CS 451 Software Engineering Winter 2009

Object-Oriented Programming Lecture 2: Classes and Objects

Unit Testing with FlexUnit. by John Mason

Transcription:

Unit Testing and JUnit

Testing Objectives Tests intended to find errors Errors should be found quickly Good test cases have high p for finding a yet undiscovered error Successful tests cause program failure, i.e. find an undiscovered error. Tests should be mutually exclusive and exhaustive Minimal set of test cases needs to be developed because exhaustive testing not possible

Unit Testing A unit is typically a method/class/a cluster Testing done to each unit, in isolation, to verify its behavior Typically the unit test will establish some sort of artificial environment and then invoke methods in the unit being tested It then checks the results returned against some known value When the units are assembled we can use the same tests to test the system as a whole

Unit Testing Tool for java : JUnit JUnit is a framework for writing tests www.junit.org JUnit was written by Erich Gamma (of Design Patterns fame) and Kent Beck (creator of XP methodology) JUnit uses Java s reflection capabilities (Java programs can examine their own code) JUnit features includes: Test fixtures for sharing common test data Assertions for testing expected results Test suites for easily organizing and running tests Graphical and textual test runners JUnit is not yet included in Sun s SDK, but an increasing number of IDEs include it BlueJ, JBuilder, Eclipse, DrJava etc.now provide JUnit support

Structure of a JUnit test class Suppose you want to test a class named Complex public class ComplexTest extends junit.framework.testcase { This is the unit test for the Complex class; it declares (and possibly defines) values used by one or more tests publiccomplextest() { This is the default constructor protected void setup() Creates a test fixture by creating and initializing objects and values protected void teardown() Releases any system resources used by the test fixture public void testadd(), public void testequals(), etc. These methods contain tests for the Complex class methods add(), Equals(), etc.

public class Complex { int real_part; int imaginary_part; public Complex(int r, int i) { real_part=r; imaginary_part=i; Example: Complex public Complex() { Class real_part=0; imaginary_part=0; public boolean Equal(Complex c) { boolean result = false; if ((real_part==c.get_r()) && (imaginary_part==c.get_i())) result=true; return result; public Complex Add(Complex c) { Complex result = new Complex(c.get_r()+real_part,c.get_i()+imaginary_part); return result; public int get_r() { return real_part; public int get_i() { return imaginary_part;

Using JUnit (Create Fixture) public class ComplexTest extends TestCase { Complex c1; Complex c2; protected void setup() { c1 = new Complex(7,3); c2 = new Complex(12,6); protected void teardown(){

Using JUnit (Add Test Cases) public void testadd() { Complex result = c1.add(new Complex(5,3)); assertequals(result.get_r(),c2.get_r()); assertequals(result.get_i(),c2.get_i()); public void testequal(){ asserttrue(!c2.equal(c1)); asserttrue(c1.equal(new Complex(7,3))); Note that each test begins with a brand new c1 and c2 This means you don t have to worry about the order in which the tests are run

Two alternative to run Your tests Implicit - TestRunner uses reflection to determine the tests to be run i.e. methods starts with test prefix Explicit public static void main(string [] args) { junit.textui.testrunner.run(complextest.class); - use of a public static method of TestCase class named suite() - explicitly naming the tests to be run public static Test suite() { TestSuite suite = new TestSuite(); suite.addtest(new ComplexTest( testadd )); suite.addtest(new ComplexTest( testequal )); return suite; public static void main(string[] argv){ junit.textui.testrunner.run(suite());

Writing a Test Case To write a test case, follow these steps: 1.Define a subclass of TestCase. 2.Override the setup() method to initialize object(s) under test. 3.Override the teardown() method to release object(s) under test. 4.Define one or more testxxx() methods that exercise the object(s) under test. 5.Define a suite() factory method that creates a TestSuite containing all the testxxx() methods of the TestCase. 6.Define a main() method that runs the TestCase.

More Assert methods I assertequals(expected, actual) assertequals(string message, expected, actual) This method is heavily overloaded: arg1 and arg2 must be both objects or both of the same primitive type For objects, uses your equals method, if you have defined it properly, as public boolean equals(object o) --otherwise it uses == assertsame(object expected, Object actual) assertsame(string message, Object expected, Object actual) Asserts that two objects refer to the same object (using ==) assertnotsame(object expected, Object actual) assertnotsame(string message, Object expected, Object actual) Asserts that two objects do not refer to the same object

More Assert methods II assertnull(object object) assertnull(string message, Object object) Asserts that the object is null assertnotnull(object object) assertnotnull(string message, Object object) Asserts that the object is null fail() fail(string message) Causes the test to fail and throw an AssertionFailedError Useful for testing Exceptions

Using Junit Download latest version (3.8.1) from: www.junit.org Setup classpath to junit.jar Write TestCase classes and organize them (Import junit.framework.*) Include appropriate JUnit TestRunner in main()

JUnit GUI Test Runners Figure 1: A Successful Run (awtui) Figure 2: An Unsuccessful Run (swingui)

Unit Testing (without tool support) public class Complex { int real_part; int imaginary_part; public Complex(int r, int i) { real_part=r; imaginary_part=i; public Complex() { real_part=0; imaginary_part=0; public boolean Equal(Complex c) { boolean result = false; if ((real_part==c.get_r()) && (imaginary_part==c.get_i())) result=true; return result; public Complex Add(Complex c) { Complex result = new Complex(c.get_r()+real_part,c. get_i()+imaginary_part); return result; public int get_r() { return real_part; public int get_i() { return imaginary_part; Complex Class: revisited public static void main(string[] argv) { Complex c1 = new Complex(7,3); Complex c2 = new Complex(12,6); Complex result = c1.add(new Complex(5,3)); if (result.get_r()==c2.get_r() && result.get_i()==c2.get_i()) System.out.println( Addition test Passed ); else System.out.println( Addition test Failed ); if (!c2.equal(c1)) System.out.println( Equality test I Passed ); else System.out.println( Equality test I Failed );

Organizing and Running Tests To run your tests, you need: An instance of a TestRunner class. An instance of your test class (named MyTestClass for the purposes of this example) containing the tests you want to run. MyTestClass must extend junit.framework.testcase. Some way of telling the chosen TestRunner instance which tests on your MyTestClass instance to run.

Organizing Tests Hierarchies: An Example: import junit.framework.testcase; public class MyTestClass extends TestCase { public MyTestClass(String name) { super(name); public void runtest() { testturnleft(); public void testturnleft() {... code here... import junit.framework.testcase; public class CalculatorTest extends TestCase { public CalculatorTest(String name) { super(name); public void runtest() { testisdivisor(); public void testisdivisor() {... code here... import junit.framework.testcase; public class MyThirdTestClass extends TestCase { public MyThirdTestClass(String name) { super(name); public void test1() {... code here... public void test2() {... code here...

A hierarchy of Tests to run public static suite() { TestSuite testsuite = new TestSuite(); testsuite.addtest(new MyTestClass("testTurnLeft")); testsuite.addtest(new CalculatorTest("testIsDivisor")); testsuite.addtest(new TestSuite(MyThirdTest.class)); return testsuite;

Problems with unit testing JUnit is designed to call methods and compare the results they return against expected results This works great for methods that just return results, but some methods have side effects To test methods that do output, you have to capture the output It s possible to capture output, but it s an unpleasant coding chore To test methods that change the state of the object, you have to have code that checks the state It s a good idea in any case to write self-tests for object validity It isn t easy to see how to unit test GUI code

Conclusions Unit Testing is the place to identify and remove errors at the earliest Effective Automated tests can be written to test most of the units, if not all Unit Testing Frameworks (UTF), like JUnit are quite useful in writing, executing and organizing unit tests for incremental code development and change management.

JUnit in Eclipse To create a test class, select File New Other... Java, JUnit, TestCase and enter the name of the class you will test Fill this in This will be filled in automatically

Running JUnit Second, use this pulldown menu First, select a Test class Third, Run As JUnit Test

Results Your results are here