Unit Testing Test First, Code Second. Understanding Why We Test First This seems backwards, if you test first there is nothing to test Testing first requires.

Slides:



Advertisements
Similar presentations
Test-First Programming. The tests should drive you to write the code, the reason you write code is to get a test to succeed, and you should only write.
Advertisements

Computer Science 209 Testing With JUnit. Why Test? I don ’ t have time, I ’ ve got a deadline to meet The more pressure I feel, the fewer tests I will.
J-Unit Framework.
What is Unit Testing? How TDD Works? Tsvyatko Konov Telerik Corporation
Annoucements  Next labs 9 and 10 are paired for everyone. So don’t miss the lab.  There is a review session for the quiz on Monday, November 4, at 8:00.
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.
Well-behaved objects 4.0 Testing. 2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to.
1 Software Testing and Quality Assurance Lecture 23 – JUnit Tutorial.
JUnit, Revisited 17-Apr-17.
22-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.
23-Jun-15 Unit Testing in Ruby. Programming methodologies The grim facts: The majority of large programming projects fail Projects that succeed are usually.
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.
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.
Testing HCI Usability Testing. Chronological order of testing Individual program units are built and tested (white-box testing / unit testing) Units are.
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.
TDD,BDD and Unit Testing in Ruby
Software Testing Sudipto Ghosh CS 406 Fall 99 November 9, 1999.
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:
Lesson 7 Unit Testing /JUnit/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Computer Science and Engineering College of Engineering The Ohio State University JUnit The credit for these slides goes to Professor Paul Sivilotti at.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
Introduction to Testing 1. Testing  testing code is a vital part of the development process  the goal of testing is to find defects in your code  Program.
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.
© ALEXANDRE CUVA  VERSION 2.00 Test Driven Design.
Testing. RHS – SOC 2 Testing So far, we have not really created tests in a systematic manner Testing has been more like ”probing” Making a thorough test.
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.
SWE 619 © Paul Ammann Procedural Abstraction and Design by Contract Paul Ammann Information & Software Engineering SWE 619 Software Construction cs.gmu.edu/~pammann/
Dr. Tom WayCSC Testing and Test-Driven Development CSC 4700 Software Engineering Based on Sommerville slides.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Testing in NetBeans. SWC Testing The ideal test: When the test is passed, the product is ready for delivery! Ideal – but (almost) impossible –Number of.
1.  Writing snippets of code that try to use methods (functions) from your program.  Each snippet should test one (and only one) function......by calling.
A Practical Guide To Unit Testing John E. Boal TestDrivenDeveloper.com.
(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.
TEST-1 6. Testing & Refactoring. TEST-2 How we create classes? We think about what a class must do We focus on its implementation We write fields We write.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
A tool for test-driven development
Week81 APCS-AB: Java Unit Testing Information today from “Unit Testing in BlueJ” October 28, 2005.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
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.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
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.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Unit Testing. F-22 Raptor Fighter Manufactured by Lockheed Martin & Boeing How many parts does the F-22 have?
Unit Testing with FlexUnit
Justin Bare and Deric Pang with material from Erin Peach, Nick Carney, Vinod Rathnam, Alex Mariakakis, Krysta Yousoufian, Mike Ernst, Kellen Donohue Section.
JUnit Testing Why we do this and how we can get better.
Today protected access modifier Using the debugger in Eclipse JUnit testing TDD Winter 2016CMPE212 - Prof. McLeod1.
Test automation / JUnit Building automatically repeatable test suites.
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Unit Testing.
Software Construction Lab 10 Unit Testing with JUnit
Computer Science 209 Testing With JUnit.
CompSci 230 Software Construction
Test-first development
Test Driven Lasse Koskela Chapter 2: Beginning TDD
Test-driven development (TDD)
Testing and Test-Driven Development CSC 4700 Software Engineering
Credit to Eclipse Documentation
Test-Driven Development
CS 240 – Advanced Programming Concepts
CSE 143 Lecture 5 More ArrayIntList:
Test-Driven Development
Presentation transcript:

Unit Testing Test First, Code Second

Understanding Why We Test First This seems backwards, if you test first there is nothing to test Testing first requires you to think differently – Some claim the most important piece of the agile development process – Can be difficult to embrace – How can this even be done with nothing to test?

Tests before Code Cooking recipes have been compared to software programs/algorithms – How do you know when the turkey is done? – Without a test you’ll just be guessing at when you’re done (and risk salmonella) Building inspector does the same thing – Set of criteria for the building to pass, even if the building doesn’t exist yet Programming – Write the test case first – Forces you into a simple, bottom-up design as you test individual cases first and then later the integration of those cases

Writing a Test Case First, decide on subtask to accomplish – Should be small and require a simple test case (or cases) Simple example – Need to write code to find the largest of three integers – Write test case first to indicate success or failure of the code you will write

Simple Test Case public void testMaxOfThreeInts() { if (maxOfThreeInts(1,7,3) == 7) { System.out.println("Passed MaxOfThreeInts Test"); } else { System.out.println("Failed maxOfThreeInts Test"); }

Simple Test Case, Expanded public void testMaxOfThreeInts() { if (maxOfThreeInts(1,7,3) == 7) { if (maxOfThreeInts(6,1,4) == 6) { System.out.println("Passed MaxOfThreeInts Test"); } else { System.out.println("Failed maxOfThreeInts Test"); } else { System.out.println("Failed maxOfThreeInts Test"); } If desired, we can add more tests for the code, to test more conditions. Don’t add too many or the test case can become too complex. “Smoke test”.

Better Version Use assert which throws an exception if the expression in parenthesis is not true – Appropriate for internal invariants – NOT appropriate to take the place of argument checking, work your app would do for correct operation – For Java, must run with –ea flag public void testMaxOfThreeInts() { assert(maxOfThreeInts(1,7,3) == 7) : "Failed for 1,7,3"; assert(maxOfThreeInts(7,1,3) == 7) : "Failed for 7,1,3"; }

Writing Code Being Tested Next we would fill in the code to be tested. If desired we could start with a stub to allow the test case to run: Then we fill in the code and test it: public int maxOfThreeInts(int num1, int num2, int num3) { return num1; } public int maxOfThreeInts(int num1, int num2, int num3) { int max = num1; if ((num2 >= num1)) && (num2 >= num3)) max = num2; if ((num3 >= num1)) && (num3 >= num2)) max = num3; return max; }

Slightly More Complex Example Test to see if entered password matches that of the stored password for a graphical password scheme

Graphical Password Test Already defined: class Point { private int x,y; public Point(int x, int y) {... } public double distance(Point otherPoint) {... } } Header: private boolean passwordMatch(ArrayList actual, ArrayList entered) What tests to write?

Graphical Password Test private boolean passwordMatch(ArrayList actual, ArrayList entered)

Next we write the code private boolean passwordMatch(ArrayList actual, ArrayList entered) { if (actual.size() != entered.size()) { return false; } for (int i=0; i<actual.size(); i++) { Point p1 = actual.get(i); Point p2 = entered.get(i); double d = p1.distance(p2); if (d > CIRCLEDIAMETER/2) { return false; } return true; } Tests can help drive the creation of the code; e.g. if wrote test for different sized ArrayLists

Exhaustive Testing This would be if we wrote test cases to handle all input scenarios – Not feasible in most cases – Too many input combinations, tests become too complicated and difficult, too time consuming Practical alternative is representative testing – Pick cases that are representative of a segment of the code – Pick cases on the boundary conditions and outside boundary conditions (i.e. should cause errors) – We’ll say more about choosing test conditions for good coverage later

Testing First is Hard! You may “reinterpret” the process by writing the code first and then immediately afterwards write the test – Not OK If you find code without a test, stop, write the test, and continue – Work harder to think of testing as the first step when tackling a subtask – The act of writing the test case will drive the design and force you to focus on the immediate subtask, eliminate ancillary issues, and give a different perspective on writing the code

Developing a Test Suite The collection of all tests is called the Test Suite Immediately provides a system status report – Use as a roadmap to locate problems – If testing is not done first, it is easy to have gaps in the system Test suite grows naturally and incrementally using the test-first methodology The test suite can grow to be quite large – Must be automated

Automated Testing Tests must be automated so they can be re-run in case new code breaks old code Must be – Fully automated (click a button to run them all) – Interpret Results (visual feedback) – Descriptive Error Messages (so you know where it failed) – Fast Testing frameworks like JUnit (Java), NUnit (.NET), or XUnit (C++) can help Will walk through JUnit briefly in class Can google for JUnit/NUnit tutorials online

Rationale Behind Testing First Forces programmers to think about code before writing it – By extension, guides design of the overall system If you wrote the code first and it seems to work, would you bother writing a test for it? Gives immediate, useful feedback Test suite becomes an invaluable, custom tool to gauge the health and progress of the system

Testing First Forces Simplicity Writing test phase – State test cases as simply as possible – Find enough representative test cases to cover the code Writing code – Goal becomes making the test pass – Perform least amount of work to reasonably make the test pass Might be ugly code at first, but if it works it can be refactored later

Simplicity drives the Design Simple bottom-up development leads to a good high-level design Doesn’t dismiss system design, but promotes designing and building the system in tandem Argument: cumulative effect of making lots of good, small local decisions leads to a good overall, global design – Emergent behavior; we get an emergent design that can be robust

Testing First Clarifies the Task A test is a small, self-contained action It becomes an example to help understand what the code needs to do Also acts as a checkpoint; if you don’t understand the problem well enough to write a test case, you aren’t ready to write the code Might grapple on how to write the test, but the time also helps you write the code

Testing First Frees You from On-the-fly Editing On-the-fly editing: You’re coding along then see a different way of implementing the code. – Scrap approach or keep it? – Hit on productivity either way Testing first eliminates distraction – Aim for simplest, correct solution – Later, the code can be re-examined – No immediate worry about readability, efficiency, maintainability, speed, size, cleverness, etc. The focus is on making simple code to pass the test. After code is written it is fair game for change

Test Suites and Refactoring A major refactoring could involve changing code in lots of classes and methods – Potential for everything to horribly break Test Suite provides a safety net and provide confidence in large, complex changes Can experimentally probe the structure and dependencies by making tentative changes

Testing First Provides Documentation Test cases provide useful documentation – Encapsulates the developer’s intent while writing the code Future maintainers get chronology of the development and useful diagnostic tool to guide future changes

Fixing Broken Test Cases You modify code or introduce a bug and as a result, tests don’t run correctly. What now? Goal is to make the tests pass – Might require refactoring the test cases themselves to match new code signatures – Might require searching through the code to find out why the test case fails

Adding Missing Tests If you ever find a bug that the test suite doesn’t catch, then you must write a test that exposes the deficiency before fixing the code – Causes the tests to reflect the error condition – Prevents missing the problem in the future if it creeps back in somehow

Tests Suites and Sanity Test suites psychologically help the team’s frame of mind – Successful passing of tests strokes your inner programmer – Stronger boost when you see a new/better/more efficient way to write your code, and can see that all of the tests still pass

JUnit and NetBeans Demo Integrated into NetBeans – Slightly different process if not using an IDE; have to import Junit, make a test class, extend TestCase – Also integrated with Eclipse and other IDE’s 1.Create project 2.Create class for code that will be tested – Can make a test case with no corresponding class, but I think it’s a bit easier to make the class first 3.Select the class in the project view and under T)ools select Create JUnit Tests

JUnit Creating a JUnit Test Class has “Test” at end to distinguish it as a test Can leave default code generation If there are methods in the class, JUnit will create tests for each one – Can be useful to write an empty method to be tested first, with just the header, to make it easier to generate the test

Test public static void setUpClass() throws Exception { public static void tearDownClass() throws Exception { public void setUp() { public void tearDown() { } /** * Test of main method, of class HelloWorld. public void testMain() { System.out.println("main"); String[] args = null; HelloWorld.main(args); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } Run once for the test class Run for every test Test; Add multiple test methods

Running Tests Select “Test ” under the “R)un” menu Or right-click the test class and select “Run”

Determining Success or Failure The Assert class has the following methods: – assertEquals: Overloaded to test if an actual value matches the expected one. First parameter can be a String with a message. assertEquals(“Number mismatch”, 3, 3); // Passes if 3 == 3 – assertFalse: Use this if you know the function will always return false (fails if it receives true) – assertNotNull: If your method return null in the event of failure use this to check to see if it succeeds – assertNotSame: If your method is supposed to return an element from a list you can use this to check if the element returned is the one from the actual list – assertNull: If your method return null in the event of failure use this to check to see if it fails – fail: Will fail the test, use this in conjunction with conditionals – failNotEquals: Essentially the same as assertEquals but will fail the test if they arent equal instead of causing an error – failNotSame: Essentially the same as assertNotSame except instead of causing an error it will cause a failure

Running Tests IDE displays results of each test; click on a test to get more details and jump straight to the failed case

Happy Testing! JUnit makes it easy to create, maintain, run tests Tests are kept separate from the actual project so they don’t interfere with the “real” code If you don’t want to use a test framework you could make your own with a little extra work – Separate class with a main() that invokes all the methods for the tests, outputs or asserts errors, etc.