Unit Testing. and. JUnit



Similar documents
Unit Testing and JUnit

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

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

Unit Testing JUnit and Clover

Approach of Unit testing with the help of JUnit

JUnit. Introduction to Unit Testing in Java

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

TESTING WITH JUNIT. Lab 3 : Testing

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

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

Java course - IAG0040. Unit testing & Agile Software Development

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

Unit-testing with JML

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

Software Quality Exercise 2

JUnit - A Whole Lot of Testing Going On

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

Testing, Debugging, and Verification

Java Unit testing with JUnit 4.x in Eclipse

Using JUnit in SAP NetWeaver Developer Studio

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

CI/CD Cheatsheet. Lars Fabian Tuchel Date: 18.March 2014 DOC:

Unit Testing & JUnit

Tools for Integration Testing

Unit Testing with FlexUnit. by John Mason

Effective unit testing with JUnit

Test Driven Development

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

Software project management. and. Maven

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

Writing Self-testing Java Classes with SelfTest

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

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

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

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

Hands on exercise for

Capabilities of a Java Test Execution Framework by Erick Griffin

Java Interview Questions and Answers

CS506 Web Design and Development Solved Online Quiz No. 01

A Practical Guide to Test Case Types in Java

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

Introduction to unit testing with Java, Eclipse and Subversion

Software project management. and. Maven

Aspect Oriented Programming. with. Spring

Tes$ng Hadoop Applica$ons. Tom Wheeler

Upping the game. Improving your software development process

Test-Driven Development

Testing Tools Content (Manual with Selenium) Levels of Testing

Going Interactive: Combining Ad-Hoc and Regression Testing

Tutorial IV: Unit Test

AP Computer Science Java Subset

Maven or how to automate java builds, tests and version management with open source tools

Chapter 1: Web Services Testing and soapui

Build management & Continuous integration. with Maven & Hudson

LAB4 Making Classes and Objects

Tutorial for Spring DAO with JDBC

Survey of Unit-Testing Frameworks. by John Szakmeister and Tim Woods

Unit testing with JUnit and CPPUnit. Krzysztof Pietroszek

BDD FOR AUTOMATING WEB APPLICATION TESTING. Stephen de Vries

Agile.NET Development Test-driven Development using NUnit

The junit Unit Tes(ng Tool for Java

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

Tutorial for Creating Resources in Java - Client

Improve your tests with Mutation Testing. Nicolas Fränkel

Automated performance testing using Maven & JMeter. George Barnett, Atlassian Software

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

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

CS170 Lab 11 Abstract Data Types & Objects

Getting Started with the Internet Communications Engine

Software infrastructure for Java development projects

the first thing that comes to mind when you think about unit testing? If you re a Java developer, it s probably JUnit, since the

Unit Testing with zunit

Android Application Testing Guide

Tutorial 7 Unit Test and Web service deployment

Java Application Developer Certificate Program Competencies

PHPUnit Manual. Sebastian Bergmann

Test Driven Development

Kohsuke Kawaguchi Sun Microsystems, Inc. hk2.dev.java.net, glassfish.dev.java.net. Session ID

ID TECH UniMag Android SDK User Manual

Appium mobile test automation

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

Running and Testing Java EE Applications in Embedded Mode with JupEEter Framework

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

Fail early, fail often, succeed sooner!

Rake Task Management Essentials

RUP. Development Process. Iterative Process (spiral) Waterfall Development Process. Agile Development Process. Well-known development processes

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

Android Environment SDK

PHPUnit Manual. Sebastian Bergmann

Transcription:

Unit Testing and JUnit

Problem area Code components must be tested! Confirms that your code works Components must be tested t in isolation A functional test can tell you that a bug exists in the implementation pe e tato A unit test tells you where the bug is located <using> Component A <using> Test failure! But where is the bug? Component B Component C

Example: The Calculator public interface Calculator int add( int number1, int number2 ); int multiply( int number1, int number2 ); public class DefaultCalculator implements Calculator public int add( int number1, int number2 ) return number1 + number2; public int multiply( int number1, int number2 ) return number1 * number2;

Approaches to unit testing Write a small command-line program, enter values, and verify output Involves your ability to type numbers Requires skills in mental calculation Doesn t verify yyour code when its released

Approaches to unit testing Write a simple test program Objective and preserves testing efforts Requires you to monitor the screen for error messages Inflexible when more tests are needed public class TestCalculator public static void main( String[] args ) Calculator calculator = new DefaultCalculator(); int result = calculator.add( 8, 7 ); if ( result!= 15 ) System.out.println( Wrong result: + result );

The preferred solution Use a unit testing framework like JUnit A unit is the smallest testable component in an application A unit is in most cases a method A unit does not depend d on other components which h are not unit tested themselves Focus on whether a method is following its API contract Component A Unit test A <using> <using> Unit test B Component B Component C Unit test C

JUnit De facto standard for developing unit tests in Java One of the most important Java libraries ever developed Made unit testing easy and popular among developers Two techniques: Extending the TestCase class (prior to version 4) Using Java annotations (after version 4)

Extending the TestCase class Your test class should extend the TestCase class Will find and execute all methods starting with test in your test t class Lets you set up a test fixture by overriding the setup and teardown methods Provides methods for verifying method output through the Assert class

Test fixtures Tests may require common resources to be set up Complex data structures Database connections A fixture is a set of common needed resources Common setup code inside tests doesn t make sense A fixture can be created by overriding the setup and teardown methods from TestCase setup is invoked before each test, teardown after setup() testxxx() teardown() TestCase lifecycle

JUnit Calculator test Import TestCase Extend TestCase Override setup() Make methods that begin with test import junit.framework.testcase; public class CalculatorTest extends TestCase Calculator calculator; public void setup() calculator = new DefaultCalculator(); public void testadd() int sum = calculator.add( 8, 7 ); Use assertequals to assertequals( s( sum, 15 ); verify output

Example: The EventDAO Event object public class Event() private int id; private String title; private Date date; // constructors // get and set methods EventDAO interface public interface EventDAO int saveevent( Event event ); Event getevent( int id ); void deleteevent( Event event );

Fixture in EventDAOTest Overrides setup(), will be invoked before each test public class EventDAOTest extends TestCase private EventDAO eventdao; private Date date; private Event event; ; public void setup() eventdao = new MemoryEventDAO(); Instantiates an EventDAO, Date, and Event for use in test methods Calendar calendar = Calendar.getInstance(); calendar.set( 2007, Calendar.NOVEMBER, 10 ); date = calendar.gettime(); event = new Event( U2 concert, date ); Using the EventDAO and Event inside a test public void testaddevent() int id = eventdao.saveevent( event ); // more testing code follows // more test methods

The Assert class Contains methods for testing whether Conditions are true or false Objects are equal or not Objects are null or not If the test fails, an AssertionFailedError is thrown All methods have overloads for various parameter types Methods available because TestCase inherits Assert <inherits> Assert <inherits> TestCase EventDAOTest

Assert methods Method Description asserttrue( boolean ) Asserts that a condition is true. assertfalse( boolean ) Asserts that a condition is false. assertequals( Object, Object ) Asserts that two objects are equal. assertnotnull( Object ) Asserts that an object is not null. assertnull( Object ) Asserts that an object is null. assertsame( Object, Object ) Asserts that two references refer to the same object. assertnotsame( Object, Object ) Asserts that two references do not refer to the same object. fail( String ) Asserts that a test fails, and prints the given message.

Assert in EventDAOTest Descriptive name following the testxxx convention public void testsaveevent() int id = eventdao.saveevent( event ); Asserts that the saved object is equal to the retrieved object event = eventdao.getevent( id ); assertequals( event.getid(), id ); assertequals( event.gettitle(), U2 concert ); Saves and retrieves an Event with the generated identifier public void testgetevent() int id = eventdao.saveevent( event ); event = eventdao.getevent( id ); An object is expected assertnotnull( event ); Asserts that null is returned when no object exists event = eventdao.getevent( -1 ); assertnull( event );

Using Java annotations No need to follow JUnit naming conventions Tests identified by the @Test annotation Fixture methods identified by @Before and @After annotations Class-scoped fixture Identified by the @BeforeClass and @AfterClass annotations Useful for setting up expensive resources, but be careful... Ignored tests s Identified by the @Ignore annotation Useful for slow tests and tests failing for reasons beyond you Timed tests Identified by providing a parameter @Test( timeout=500 ) Useful for benchmarking and network testing

EventDAOTest with annotations Assert imported statically import static junit.framework.assert.assertequals; @Before Fixture method identified d public void init() by the @Before annotation eventdao = new MemoryEventDAO(); event = new Event( U2 concert, date ); @Test Test identified by the @Test public void saveevent() annotation. Test signature is equal to method signature. int id = eventdao.saveevent( event ); event = eventdao.getevent( id ); assertequals( event.getid(), id ); Test being ignored @Test @Ignore Public void getevent() // Test stuff...

Testing Exceptions Methods may be required to throw exceptions Expected exception can be declared as an annotation @Test( expected = UnsupportedOperationException.class ) Annotation declares that an @Test( expected = UnsupportedOperationException.class ) exception of class public void dividebyzero() UnsupportedOperationException is supposed to be thrown calculator.divide( 4, 0 );

Running JUnit Textual test runner Used from the command line Easy to run Integrate with Eclipse Convenient, integrated testing within your development environment! Integrate with Maven Gets included in the build lifecycle!

JUnit with Eclipse Eclipse features a JUnit view Provides an informativ GUI displaying test summaries Lets you edit the code, compile and test without leaving the Eclipse environment

JUnit with Maven Maven provides support for automated unit testing through JUnit Unit testing ti is included d in the build lifecyclel Verifies that existing components work when other components are added or changed Add dependency to POM to put JUnit on the classpath <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.4</version> </dependency> Execute the Maven test phase $ mvn test

JUnit with Maven Maven requires all test-class names to contain Test Standard directory for test classes is src/test/java Maven will execute all tests for you The test phase is mapped to the Surefire plugin Surefire will generate reports based on your test t runs Reports are located in target/surefire-reports

Best practises One unit test for each tested method Makes debugging easier Easier to maintain i Choose descriptive test method names TestCase: Use the testxxx naming convention Annotations: Use the method signature of the tested method Automate your test execution If you add or change features, the old ones must still work Also called regression testing Test more than the happy path Out-of-domain values Boundary conditions

Advantages of unit testing Improves debugging Easy to track down bugs Facilitates t refactoring Verifies that existing features still work while changing the code structure Enables teamwork Lets you deliver tested components without waiting for whole application to finish Promotes object oriented design Requires your code to be divided in small, re-usable units Serving as developer documentation Unit ittests t are samples that tdemonstrates t usage of fthe API

Resources Vincent Massol: JUnit in Action Two free sample chapters http://www.manning.com/massol JUnit home page Articles and forum http://www.junit.org Articles http://www-128.ibm.com/developerworks/java/library/j-junit4.html http://www-128.ibm.com/developerworks/opensource/library/os-junit/