Software Construction Lab 10 Unit Testing with JUnit

Slides:



Advertisements
Similar presentations
MAHDI OMAR JUNIT TUTORIAL. CONTENTS Installation of Junit Eclipse support for Junit Using Junit exercise JUnit options Questions Links and Literature.
Advertisements

Unit Testing. Topics Motivation JUnit framework Basic JUnit tests – static methods Ensure exceptions – instance methods.
T ESTING WITH J UNIT IN E CLIPSE Farzana Rahman. I NTRODUCTION The class that you will want to test is created first so that Eclipse will be able to find.
Objectives: Test Options JUnit Testing Framework TestRunners Test Cases and Test Suites Test Fixtures JUnit.
JUnit Introduction and Advanced Features. Topics Covered  Junit Introduction  Fixtures  Test Suites  Currency Example.
24-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
TDD Test-Driven Development. JUnit 4.0 To use annotations need to import org.junit.Test To use assertion need to import org.junit.Assert.* No need to.
1 CSC/ECE 517 Fall 2010 Lec. 2 Overview of Eclipse Lectures 1.Overview 2.Installing and Running 3.Building and Running Java Classes 4.Debugging 5.Testing.
Presentation Outline What is JUnit? Why Use JUnit? JUnit Features Design of JUnit Downloading JUnit Writing Tests – TestCase – TestSuite Organizing The.
14-Jul-15 JUnit 4. Comparing JUnit 3 to JUnit 4 All the old assertXXX methods are the same Most things are about equally easy JUnit 4 makes it easier.
George Blank University Lecturer. JUnit for Test Driven Development By Vivek Bhagat, George Blank.
Programmer Testing Testing all things Java using JUnit and extensions.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
© Dr. A. Williams, Fall Present Software Quality Assurance – JUnit Lab 1 JUnit A unit test framework for Java –Authors: Erich Gamma, Kent Beck Objective:
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Unit Testing.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Lecture 6 Software Testing and jUnit CS140 Dick Steflik.
Principles of Object Oriented Programming Practical session 2 – part A.
Computer Science and Engineering College of Engineering The Ohio State University JUnit The credit for these slides goes to Professor Paul Sivilotti at.
JUnit in Action SECOND EDITION PETAR TAHCHIEV FELIPE LEME VINCENT MASSOL GARY GREGORY ©2011 by Manning Publications Co. All rights reserved. Slides Prepared.
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
CSC 216/001 Lecture 4. Unit Testing  Why is it called “unit” testing?  When should tests be written?  Before the code for a class is written.  After.
JUnit test and Project 3 simulation. 2 JUnit The testing problems The framework of JUnit A case study Acknowledgement: using some materials from JUNIT.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
JUnit Dwight Deugo Nesa Matic
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
JUnit Dwight Deugo Nesa Matic
A tool for test-driven development
By Rick Mercer with help from Kent Beck and Scott Ambler Java Review via Test Driven Development (TDD)
JUnit Eclipse, Java and introduction to Junit. Topics Covered  Using Eclipse IDE  Example Java Programs  Junit Introduction.
JUnit A framework which provides hooks for easy testing of your Java code, as it's built Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit.
JUnit. Introduction JUnit is an open source Java testing framework used to write and run repeatable tests JUnit is integrated with several IDEs, including.
S Ramakrishnan1 Systems V & V, Quality and Standards Dr Sita Ramakrishnan School CSSE Monash University.
1 Unit Testing with JUnit CS 3331 JUnit website at Kent Beck and Eric Gamma. Test Infected: Programmers Love Writing Tests, Java Report,
1 CSC 216 Lecture 3. 2 Unit Testing  The most basic kind of testing is called unit testing  Why is it called “unit” testing?  When should tests be.
2-1 By Rick Mercer with help from Kent Beck and Scott Ambler Java Review via Test Driven Development.
Unit, Regression, and Behavioral Testing Based On: Unit Testing with JUnit and CUnit by Beth Kirby Dec 13, 2002 Jules.
Unit Testing. F-22 Raptor Fighter Manufactured by Lockheed Martin & Boeing How many parts does the F-22 have?
JUnit, Bugzilla James Atlas July 24, 2008 *part of today’s slides courtesy of Dwight Deugo and Nesa Matic under the EPL.
Justin Bare and Deric Pang with material from Erin Peach, Nick Carney, Vinod Rathnam, Alex Mariakakis, Krysta Yousoufian, Mike Ernst, Kellen Donohue Section.
1 JUnit. 2 Unit Testing with JUnit If code has no automated test case written for it to prove that it works, it must be assumed not to work. An API that.
Topic: Junit Presenters: Govindaramanujam, Sama & Jansen, Erwin.
Unit Testing in Eclipse Presented by David Eisler 08/09/2014.
Introduction to Unit Testing and JUnit David Rabinowitz.
CSE 143 Lecture 14: testing.
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Advanced programming Practices
Unit Testing.
Unit Testing with JUnit
Unit testing Java programs Using JUnit
Computer Science 209 Testing With JUnit.
Software Engineering 1, CS 355 Unit Testing with JUnit
Unit testing C# classes
Overview of Eclipse Lectures
Unit Testing with JUnit
JUnit 28-Nov-18.
Test-Driven Development
Introduction to JUnit IT323 – Software Engineering II
Test Driven Development
Testing Acknowledgement: Original slides by Jory Denny.
Advanced programming Practices
CS 240 – Advanced Programming Concepts
Section 4: Graphs and Testing
CSE 143 Lecture 5 More ArrayIntList:
JUnit Reading: various web pages
Test-Driven Development
Joel Adams and Jeremy Frens Calvin College
JUnit SWE 619 Spring 2008.
JUnit Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from the Eclipse 3.0 and.
Principles of Object Oriented Programming
Presentation transcript:

Software Construction Lab 10 Unit Testing with JUnit SWAT 2010

Iterative Software development Write and execute unit tests Execute acceptance tests Write acceptance tests increment + system Prioritized functionalities “Written before” “Executed after the development” SWAT 2010

Testing with JUnit Junit is a unit test environment for Java programs developed by Erich Gamma and Kent Beck. Writing test cases Executing test cases Pass/fail? (expected result = obtained result?) Consists in a framework providing all the tools for testing. framework: set of classes and conventions to use them. It is integrated into eclipse through a graphical plug-in.

Junit (3.x and 4.x) Test code testDoubleOf2(){ //.. Production code Test framework test cases are Java code test case = “sequence of operations +inputs + expected values” Test code testDoubleOf2(){ //.. doubleOf2(); //.. } Production code int doubleOf2(){ //… }

JUnit 3.x for testing programs JUnit tests “substitute the use of main() to check the program behaviour” All we need to do is: write a sub-class of TestCase add to it one or more test methods run the test using JUnit junit.framework.*

Framework elements TestCase Base class for classes that contain tests assert*() Method family to check conditions TestSuite Enables grouping several test cases Testcase 1 Testcase 2 Testsuite Testcase 3

An example class Stack { public boolean isEmpty(){ ... } public void push(int i){ ... } public int pop(){ ... } … } An example import junit.framework.TestCase; public class StackTester extends TestCase { public StackTester(String name) { super(name); } public void testStack() { Stack aStack = new Stack(); if(!aStack.isEmpty()) { System.out.println(“Stack should be empty!”); aStack.push(10); aStack.push(-4); System.out.println(“Last element:“ + aStack.pop()); System.out.println(“First element: “ +aStack.pop()); } } Must begin with “test”

Assert*() They are public methods defined in the base class TestCase Method family to check conditions … Assert*() They are public methods defined in the base class TestCase Their names begin with “assert” and are used in test methods es. assertTrue(“stack should be empty”, aStack.empty()); If the condition is false: test fails execution skips the rest of the test method the message (if any) is printed If the condition is true: execution continues normally

Assert*() for a boolean condition assertTrue(“message for fail”, condition); assertFalse(“message”, condition); for object, int, long, and byte values assertEquals(expected_value, expression); for float and double values assertEquals(expected, expression, error); for objects references assertNull(reference) assertNotNull(reference) … obtained http://junit.org/apidocs/org/junit/Assert.html

Assert: example public void testStack() { Stack aStack = new Stack(); assertTrue(“Stack should be empty!”, aStack.isEmpty()); aStack.push(10); assertTrue(“Stack should not be empty!”,!aStack.isEmpty()); aStack.push(4); assertEquals(4, aStack.pop()); assertEquals(10, aStack.pop()); } class Stack { public boolean isEmpty(){ ... } public void push(int i){ ... } public int pop(){ ... } … }

One concept at a time … Code Modularization … public class StackTester extends TestCase { public void testStackEmpty() { Stack aStack = new Stack(); assertTrue(“Stack should be empty!”, aStack.isEmpty()); aStack.push(10); assertTrue(“Stack should not be empty!”, !aStack.isEmpty()); } public void testStackOperations() { Stack aStack = new Stack(); aStack.push(10); aStack.push(-4); assertEquals(-4, aStack.pop()); assertEquals(10, aStack.pop());

Working rule For each test case class, JUnit execute all of its public test methods i.e. those whose name starts with “test” ignores everything else … Test classes can contain “helper methods” provided that are: non public, or whose name does not begin with “test”

TestSuite junit.framework.* Groups several test cases: public class AllTests extends TestSuite { public static TestSuite suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(StackTester.class); suite.addTestSuite(AnotherTester.class); return suite; }

Test of “Exceptions” There are two cases: We expect a normal behavior and then no exceptions. We expect an anomalous behavior and then an exception.

We expect a normal behavior … try { // We call the method with correct parameters object.method("Parameter"); assertTrue(true); // OK } catch(PossibleException e){ fail(“method should not fail !!!"); } class TheClass { public void method(String p) throws PossibleException { /*... */ } }

We expect an exception … try { // we call the method with wrong parameters object.method(null); fail(“method should fail!!"); } catch(PossibleException e){ assertTrue(true); // OK } class TheClass { public void method(String p) throws PossibleException { /*... */ } }

SetUp() and tearDown() setUp() method initialize object(s) under test. called before every test method tearDown() method release object(s) under test called after every test case method. ShoppingCart cart; Book book; protected void setUp() { cart = new ShoppingCart(); book = new Book(“JUnit", 29.95); cart.addItem(book); } …

Junit in eclipse - Setup Create a new project Open project’s property window (File -> Properties) Select: Java build path Select: libraries Add Library Select Junit Select the type 3.x or 4.x

Create a new JUnit test case Eclipse Menu File Edit Source Refactor Navigate Search Project Run Window Help File New Junit Test Case Set the parameters: Junit 3.x or 4.x name of the class etc. Finish

Run as JUnit Test Eclipse Menu Run Run As File Edit Source Refactor Navigate Search Project Run Window Help Run Run As Junit Test

expected <-3> but was <-4> Red / Green Bar Fail Pass expected <-3> but was <-4>

JUnit 3.x and JUnit 4.x Most things are about equally easy JUnit 4 can still run JUnit 3 tests All the old assertXXX methods are the same JUnit 4 has some additional features JUnit 4 provides protection against infinite loops Junit 4 uses annotations (@) SWAT 2010

From JUnit 3.x to 4.x JUnit 4 requires Java 5 or newer Don’t extend junit.framework.TestCase; just use an ordinary class Import org.junit.* and org.junit.Assert.* Use a static import for org.junit.Assert.* Static imports replace inheritance from junit.framework.TestCase Use annotations instead of special method names: Instead of a setUp method, put @Before before some method Instead of a tearDown method, put @After before some method Instead of beginning test method names with ‘test’, put @Test before each test method SWAT 2010

Annotations in J2SE J2SE 5 introduces the Metadata feature (data about data) Annotations allow you to add decorations to your code (remember javadoc tags: @author ) Annotations are used for code documentation, compiler processing (@Deprecated ), code generation, runtime processing New annotations can be created by developers http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html

Annotations in J2SE … an example …. @Override — it is a predefined annotation used by the Java compiler It informs the compiler that the element (a method) is meant to override an element declared in a superclass // mark method as a superclass method // that has been overridden @Override public int overriddenMethod() { …} While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails in correctly overriding the original method in its superclass, the compiler generates an error.

Junit 4.x for testing programs Import the JUnit 4 classes you need import org.junit.*; import static org.junit.Assert.*; Declare your (conventional) Java class public class MyProgramTest { Declare any variables you are going to use, e.g., an instance of the class being tested MyProgram program; int [ ] array; int solution; SWAT 2010

Junit 4.x for testing programs (2) If needed, define one method to be executed just once, when the class is first loaded. For instance, when we need to connecting to a database @BeforeClass public static void setUpClass() throws Exception { // one-time initialization code } If needed, define one method to be executed just once, to do cleanup after all the tests have been completed @AfterClass public static void tearDownClass() throws Exception { // one-time cleanup code } SWAT 2010

Junit 4.x for testing programs (3) If needed, define one or more methods to be executed before each test, e.g., typically for initializing values @Before public void setUp() { program = new MyProgram(); array = new int[] { 1, 2, 3, 4, 5 }; } If needed, define one or more methods to be executed after each test, e.g., typically for releasing resources (files, etc.) @After public void tearDown() { } SWAT 2010