Programmer Testing Testing all things Java using JUnit and extensions.

Slides:



Advertisements
Similar presentations
JUnit Tutorial Hong Qing Yu Nov JUnit Tutorial The testing problems The framework of JUnit A case study JUnit tool Practices.
Advertisements

Unit Testing Australian Development Centre Brisbane, Australia.
1 Unit Testing with JUnit CS 3331 Fall 2009 Kent Beck and Eric Gamma. Test Infected: Programmers Love Writing Tests, Java Report, 3(7):37-50, Available.
J-Unit Framework.
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.
JUnit intro Kalvis Apsitis. What are “Programmer Tests”? Programmer Testing is the testing performed by a developer with the goal of verifying the correct.
Ch. 2 Exploring core JUnit. This chapter covers ■ Using the core JUnit classes ■ Understanding JUnit mechanisms ■ Understanding the JUnit lifecycle.
Objectives: Test Options JUnit Testing Framework TestRunners Test Cases and Test Suites Test Fixtures JUnit.
JUnit Automated Software Testing Framework Paul Ammann & Jeff Offutt Thanks in part to Aynur Abdurazik.
Integration Testing When testing a module in isolation –Called modules need to be replaced –Tested module needs to be called A D ′ E ′ main driver module.
Approach of Unit testing with the help of JUnit Satish Mishra
JUnit test distribution Bettina Scharpf ACM 2 University of Applied Science Furtwangen.
JUnit. What is unit testing? A unit is the smallest testable part of an application. A unit test automatically verifies the correctness of the unit. There.
1 Software Testing and Quality Assurance Lecture 23 – JUnit Tutorial.
JUnit, Revisited 17-Apr-17.
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.
Writing a Unit test Using JUnit At the top of the file include: import junit.framework.TestCase; The main class of the file must be: public Must extend.
Testowanie kodu Bartosz Baliś, Na podstawie prezentacji Satisha Mishra Iana Sommerville Erica Braude.
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.
Unit Testing Discussion C. Unit Test ● public Method is smallest unit of code ● Input/output transformation ● Test if the method does what it claims ●
George Blank University Lecturer. JUnit for Test Driven Development By Vivek Bhagat, George Blank.
Unit Testing Using PyUnit Monther Suboh Yazan Hamam Saddam Al-Mahasneh Miran Ahmad
Lesson 7 Unit Testing /JUnit/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
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.
Testing in Extreme Programming
Unit Testing Bartosz Walter Software Engineering Lecture XXX.
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
Unit testing Unit testing TDD with JUnit. Unit Testing Unit testing with JUnit 2 Testing concepts Unit testing Testing tools JUnit Practical use of tools.
Software Engineering 1 Object-oriented Analysis and Design Chap 21 Test-Driven Development and Refactoring.
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.
(1) Unit Testing and Test Planning CS2110: SW Development Methods These slides design for use in lab. They supplement more complete slides used in lecture.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
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
JUnit Jumpstart © Manning Publications.
JUnit Don Braffitt Updated: 10-Jun-2011.
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.
JUnit A Unit Testing Framework for Java. The Objective Introduce JUnit as a tool for Unit Testing Provide information on how to: Install it Build a test.
JUnit in Action SECOND EDITION PETAR TAHCHIEV FELIPE LEME VINCENT MASSOL GARY GREGORY ©2011 by Manning Publications Co. All rights reserved.
Unit, Regression, and Behavioral Testing Based On: Unit Testing with JUnit and CUnit by Beth Kirby Dec 13, 2002 Jules.
Test a Little, Code a Little Colin Sharples IBM Global Services New Zealand Colin Sharples IBM Global Services New Zealand.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Automated Testing in Sakai Testing applications and services in isolation and in context Josh Holtzman, UC Berkeley David Haines, University of Michigan.
Unit Testing with FlexUnit
Topic: Junit Presenters: Govindaramanujam, Sama & Jansen, Erwin.
Today protected access modifier Using the debugger in Eclipse JUnit testing TDD Winter 2016CMPE212 - Prof. McLeod1.
Software Construction Lab 10 Unit Testing with JUnit
Don Braffitt Updated: 26-Mar-2013
Unit testing Java programs Using JUnit
Computer Science 209 Testing With JUnit.
Introduction to JUnit CS 4501 / 6501 Software Testing
Introduction to JUnit IT323 – Software Engineering II
Joel Adams and Jeremy Frens Calvin College
JUnit Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from the Eclipse 3.0 and.
Test-Driven Development
JUnit Tutorial Hong Qing Yu Nov 2005.
Presentation transcript:

Programmer Testing Testing all things Java using JUnit and extensions

The Big Why “If you don’t have tests, how do you know your code is doing the thing right and doing the right thing ?”

What are “Programmer Tests”? Programmer Testing is the testing performed by a developer with the goal of verifying the correct functioning of her code Programmer Tests are automated unit tests that exercise program units such as classes and methods, not the complete features or requirements supported by the software as a whole Important distinction: if it’s not automated, it’s not really programmer testing – that’s exploratory testing.

Safety Net Having a good test coverage with an automated unit test harness… –prevents a system from becoming legacy(*), and –enables effective refactoring, because it also –prevents regression Metaphor: Mold * Michael Feathers defines “legacy code” as code without tests

Available tools for Java JUnit –The de facto Java unit testing framework –Extremely simple –Plenty of extensions for J2EE, for example TestNG –Very close to JUnit but not quite instead of naming conventions

JUnit What is the difference between a framework and a library? Is JUnit ( a framework or a library?

JUnit 101 Essential concepts: –Test suite: Java class that extends junit.framework.TestSuite or implements a static method named suite(), returning a TestSuite –Test case: Java class extending junit.framework.TestCase –Test fixture: the initial state of a Test Case, consisting of the member variables initialized through a method named setUp() –Test method: a method of a TestCase class of which signature looks like “public void testFoo()”, representing a single logical test

TestCase lifecycle setUp() gets called once before each test method is executed tearDown() gets called once after each test method has been executed – regardless of whether the test passed or failed (or threw some other exception). Each testSomething() method gets called exactly once – in an arbitrary order! The same instance of a TestCase may or may not be used for executing the tests – don’t depend on the constructor, use setUp() for setup!

Java 1.5 annotations JUnit 3.8 Java 1.4 public void setUp() {... } public void testSomething() {... } public void tearDown() {... } JUnit 4.1 Java someSetUp() {... public void something() {... public void someTearDown () {... }

What else is new in JUnit 4.1? Parametrized tests - same testcase is repeated for various argument sets. Annotated way to write test suites and to filter out testcases which (not) to execute

JUnit 101: Simple TestCase (1) import junit.framework.*; public class TestCalculator extends TestCase { protected void setUp() { super.setUp(); } protected void tearDown() { super.tearDown(); }

JUnit 101: Simple TestCase (2) import junit.framework.*; public class TestCalculator extends TestCase { private Calculator calculator; protected void setUp() { super.setUp(); calculator = new Calculator(); }

JUnit 101: Simple TestCase (3) import junit.framework.*; public class TestCalculator extends TestCase { private Calculator calculator; public void testAddingPositiveIntegers() { int expected = 5; int actual = calculator.add(2, 3); assertEquals(“2 + 3 should be 5”, expected, actual); }

JUnit 101: Simple TestCase (4) import junit.framework.*; public class TestCalculator extends TestCase { private Calculator calculator; protected void setUp() { … } protected void tearDown() { … } public void testAddingPositiveIntegers() { … } public void testAddingNegativeIntegers() { … } public void testAddingZeroes() { … } public void testAddingPositiveToNegative() { … } }

JUnit 101: Simple TestSuite (1) import junit.framework.*; public class CalculatorTestSuite extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(CalculatorIntegerTest.class); suite.addTest(CalculatorFloatingPointTest.class); suite.addTest(CalculatorLogarithmsTest.class); return suite; }

What if I need to do something expensive in setUp()? If you need to perform some kind of preparations before running the test methods of a TestCase (and can’t/won’t replace the expensive stuff with a mock implementation), you need to wrap your TestCase with a junit.extensions.TestSetup decorator class.

Wrapping TestCase into TestSetup public class InterestCalculatorTestWithTestSetup extends TestCase { private static double interestRate, loanAmount; private static int loanDuration; public static Test suite() { TestSuite suite = new TestSuite(InterestCalculatorTestWithTestSetup.class); TestSetup wrapper = new TestSetup(suite) { public void setUp() throws IOException { ResourceBundle bundle = ResourceBundler.getBundle( InterestCalculatorTestWithTestSetup.class.getName()); inrerestRate = Double.parseDouble(bundle.getString(“interest.rate”)); loanAmount = Double.parseDouble(bundle.getString(“loan.amount”)); loanDuration = Interest.parseInt(bundle.getString(“loan.duration”)); } }; return wrapper; } public void testInterestCalculation() { … } }

Assertions We already saw one assertion in action, the assertEquals() method There are a bunch others – take a look at the Javadocs for junit.framework.TestCase at The most often used assertions – assertEquals(), assertEquals(), assertNull(), assertSame() and their opposites – are enough for most situations and the rest you can easily write on your own.

What happens when an assertion fails? The assertions throw a junit.framework.AssertionFailedError when they fail. JUnit’s TestRunner catches these (runtime)exceptions and tags the test as “failure” for later reference. If a test throws any other exception (e.g. NullPointerException), JUnit again catches these but tags the test as “error” instead of “failure”.

Mock Objects At some point, you will face a problem where the class/method you should be testing needs to collaborate with an object that is either difficult to create/obtain or simply sooo slooow that your test takes forever to execute (even a 100ms adds up when you’ve got thousands of tests…). The solution for this kind of problems is often to use a mock object.

What are Mock Objects? A mock object is an object that claims to implement an interface but doesn’t really. There are variations on what the “doesn’t really” part actually means (these variations are called “fake”, “stub” and “mock”) but for now, we’ll just call them all mock objects. Since there’s nothing like a good example…

Example: Mock Objects public class Item { public float getPriceAfterDiscounts(PricingService ps, DiscountService ds) { float basePrice = ps.getPriceFor(this); float discountedPrice = ds.applyDiscounts(this, basePrice); return discountedPrice; } public interface PricingService { float getPriceFor(Item item); } public interface DiscountService { float applyDiscounts(Item item, float basePrice); }

How to test that without the real PricingService & DiscountService? public class TestItemUsingMockObjects extends TestCase { private Item item; private PricingService pricingService; private DiscountService discountService; protected void setUp() { item = new Item(); pricingService = new PricingService() { public float getPriceFor(Item item) { return 12.34f; } }; discountService = new DiscountService() { public float applyDiscounts(Item item, float basePrice) { … } }; } public void testCalculateDiscountsOnBasePrice() { assertEquals(10.95f, item.getPriceAfterDiscounts(pricingService, discountService); }

Static vs. Dynamic Mocks That example used “static” mock objects – the other school of mock objects is “dynamic” mock objects Static mock objects fake their own behavior while dynamic mock objects also verify that the class under test collaborated with the mock objects as expected Let’s see an example to illustrate this behavior-oriented approach to using mock objects (we’ll use the EasyMock framework but there are some alternatives)

Using EasyMock and dynamic mock objects public class TestItemUsingMockObjects extends TestCase { private Item item; private MockControl pricingControl, discountControl; private PricingService pricingService; private DiscountService discountService; protected void setUp() { item = new Item(); pricingControl = MockControl.createControl(PricingService.class); // obtain a “remote control” pricingService = (PricingService) pricingControl.getMock(); // let EasyMock create the mock object pricingService.getPriceFor(item); // specify expected method call to our mock PricingService pricingControl.setReturnValue(12.34f); // fake the behavior by setting return value pricingControl.replay(); // switch from recording mode to replay mode // similar setup for DiscountService... } public void testCalculateDiscountsOnBasePrice() { assertEquals(10.95f, item.getPriceAfterDiscounts(pricingService, discountService); pricingControl.verify(); // verify expected interactions actually happened discountControl.verify(); // verify expected interactions actually happened }