CSE 331 SOFTWARE DESIGN & IMPLEMENTATION SOFTWARE TESTING Autumn 2011 Creative Commons Attribution-Share Alike 3.0 Unported LicenseCreative Commons Attribution-Share.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
CS 206 Introduction to Computer Science II 09 / 09 / 2009 Instructor: Michael Eckmann.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION TESTING II Autumn 2011.
JUnit, Revisited 17-Apr-17.
JUnit. Why is testing good? Due to psychological factors, programmers are bad testers. A computer can test much faster than a human Philosophy: “If it.
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.
1 Functional Testing Motivation Example Basic Methods Timing: 30 minutes.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
Software Testing Sudipto Ghosh CS 406 Fall 99 November 9, 1999.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Week 10 - Monday.  What did we talk about last time?  Method overloading  Lab 9.
© Dr. A. Williams, Fall Present Software Quality Assurance – JUnit Lab 1 JUnit A unit test framework for Java –Authors: Erich Gamma, Kent Beck Objective:
Lecture 6 Software Testing and jUnit CS140 Dick Steflik.
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.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
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.
ECS 10 10/8. Outline Announcements Homework 2 questions Boolean expressions If/else statements State variables and avoiding sys.exit(…) Example: Coin.
Testing CSE 140 University of Washington 1. Testing Programming to analyze data is powerful It’s useless if the results are not correct Correctness is.
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.
CSE 219 Computer Science III Testing. Testing vs. Debugging Testing: Create and use scenarios which reveal incorrect behaviors –Design of test cases:
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION MIDTERM REVIEW Autumn 2011.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Unit Testing 101 Black Box v. White Box. Definition of V&V Verification - is the product correct Validation - is it the correct product.
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.
(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.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CPSC 873 John D. McGregor Session 9 Testing Vocabulary.
1 CSE 331 Unit Testing with JUnit slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
JUnit. Introduction JUnit is an open source Java testing framework used to write and run repeatable tests JUnit is integrated with several IDEs, including.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
1 Unit Testing with JUnit CS 3331 JUnit website at Kent Beck and Eric Gamma. Test Infected: Programmers Love Writing Tests, Java Report,
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
Week 5-6 MondayTuesdayWednesdayThursdayFriday Testing III No reading Group meetings Testing IVSection ZFR due ZFR demos Progress report due Readings out.
PROGRAMMING TESTING B MODULE 2: SOFTWARE SYSTEMS 22 NOVEMBER 2013.
CSE 311 Foundations of Computing I Lecture 28 Computability: Other Undecidable Problems Autumn 2011 CSE 3111.
SE 433/333 Software Testing & Quality Assurance Dennis Mumaugh, Instructor Office: CDM, Room 428 Office Hours: Tuesday, 4:00 –
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Justin Bare and Deric Pang with material from Erin Peach, Nick Carney, Vinod Rathnam, Alex Mariakakis, Krysta Yousoufian, Mike Ernst, Kellen Donohue Section.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION ABSTRACT DATA TYPES Autumn 2011.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
Week 6 MondayTuesdayWednesdayThursdayFriday Testing III Reading due Group meetings Testing IVSection ZFR due ZFR demos Progress report due Readings out.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSE 143 Lecture 14: testing.
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Software Construction Lab 10 Unit Testing with JUnit
Unit Testing with JUnit
CSE373: Data Structures & Algorithms
Testing UW CSE 160 Spring 2018.
Design by Contract Fall 2016 Version.
Section 3 Graphs & Testing
CSE 143 Lecture 4 More ArrayIntList:
Section 4: Graphs and Testing
Go to pollev.com/cse143.
CSE 143 Lecture 5 More ArrayIntList:
JUnit Reading: various web pages
CSE 1020:Software Development
Lecture 14: Testing Testing used to verify object behavior through designed test suites Can test Classes – “unit” testing Object interactions – “integration”
Junit Tests.
Testing Slides adopted from John Jannotti, Brown University
Presentation transcript:

CSE 331 SOFTWARE DESIGN & IMPLEMENTATION SOFTWARE TESTING Autumn 2011 Creative Commons Attribution-Share Alike 3.0 Unported LicenseCreative Commons Attribution-Share Alike 3.0 Unported License from

Testing  “[T]he means by which the presence, quality, or genuineness of anything is determined; a means of trial.” –dictionary.comdictionary.com  A software test executes a program to determine whether a property of the program holds or doesn’t hold  A test passes [fails] if the property holds [doesn’t hold] on that run  A test suite – a set of systematically-designed software tests – executes a program to increase confidence about whether specific properties of the program hold or don’t hold  The collection of passed and failed tests as a whole provides information beyond each individual test  Just as the result of a single coin flip tells little about fairness while a longer sequence can tell more CSE 331 Autumn

Software Quality Assurance (QA) Testing plus other activities including  Static analysis (assessing code without executing it)  Proofs of correctness (theorems about program properties)  Code reviews (people reviewing others’ code)  Software process (placing structure on the development lifecycle)  …and many more ways to find problems and to increase confidence No single activity or approach can guarantee software quality CSE 331 Autumn

Kinds of Testing  Unit Testing: does each unit (class, method, etc.) do what it supposed to do?  Integration Testing: do you get the expected results when the parts are put together?  Validation Testing: does the program satisfy the requirements?  System Testing: does it work within the overall system? Today  Absolute basics of unit testing, which is our primary focus in 331, using RandomHello as an example  Some examples of JUnit – a Java unit testing mechanism that is nicely integrated into Eclipse  Later lectures: more on testing Some other testing buzzwords: alpha, beta, fuzz, random, mutation, symbolic, black & white box, coverage (statement/edge/path), model-based … and many more … CSE 331 Autumn

Black box Must choose inputs without knowledge of the implementation Unit testing A.Choose input data (“test inputs”) B.Define the expected outcome (“oracle”) C.Run the unit (“SUT” or “software under test”) on the input and record the results D.Examine results against the oracle =  oracle? Specification PreconditionPostcondition Implementation White box Can choose inputs with knowledge of the implementation 5

Black box Must choose inputs without knowledge of the implementation It’s not black-and-white, but… White box Can choose inputs with knowledge of the implementation 6  Has to focus on the behavior of the SUT  Needs an oracle  Or at least an expectation of whether or not an exception is thrown  Black-box++  Common use: coverage  Basic idea: if your test suite never causes a statement to be executed, then that statement might be buggy

sqrt example // throws: IllegalArgumentException if x < 0 // returns: approximation to square root of x public double sqrt(double x) What are some values or ranges of x that might be worth testing  x < 0 (exception thrown)  x ≥ 0 (returns normally)  around x = 0 (boundary condition)  perfect squares ( sqrt(x ) an integer), non-perfect squares  x sqrt(x)  Specific tests: say x = {-1, 0, 0.5, 1, 4} CSE 331 Autumn

Subdomains  Many executions reflect the same behavior – for sqrt, for example, the expectation is that  all x < 0 inputs will throw an exception  all x ≥ 0 inputs will return normally with a correct answer  By testing any element from each subdomain, the intention is for the single test to represent the other behaviors of the subdomain – without testing them!  Of course, this isn’t so easy – even in the simple example above, what about when x overflows? CSE 331 Autumn

Testing RandomHello  “Create your first Java class with a main method that will randomly choose, and then print to the console, one of five possible greetings that you define.”  We’ll focus on the method getGreeting, which randomly returns one of the five greetings  We’ll focus on black-box testing – we will work with no knowledge of the implementation  And we’ll focus on unit testing using the JUnit framework  Intermixing, with any luck, slides and a demo CSE 331 Autumn

Does it even run and return?  If getGreeting doesn’t run and return without throwing an exception, it cannot meet the specification JUnit tag “this is a name of test public void test_NoException(){ Run getGreeting RandomHello.getGreeting(); JUnit “test passed” (doesn’t execute if exception thrown) assertTrue(true); } A unit test is a (stylized) program! When you’re writing unit tests (and many other tests), you’re programming! CSE 331 Autumn Tests should have descriptive (often very long) names

Running JUnit tests  There are many ways to run JUnit test method, test classes, and test suites  Generally, select the method, class or suite and Run As >> JUnit Test  A green bar says “all tests pass”  A red bar says at least one test failed or was in error  The failure trace shows which tests failed and why A failure is when the test doesn’t pass – that is, the oracle it computes is incorrect An error is when something goes wrong with the program that the test didn’t check for (e.g., a null pointer exception) CSE 331 Autumn

Does it return one of the greetings?  If it doesn’t return one of the defined greetings, it cannot satisfy the public void testDoes_getGreeting_returnDefinedGreeting() { String rg = RandomHello.getGreeting(); for (String s : RandomHello.greetings) { if (rg.equals(s)) { assertTrue(true); return; } fail("Returned greeting not in greetings array"); } CSE 331 Autumn

A JUnit test class import org.junit.*; import static org.junit.Assert.*; public class RandomHelloTest() public void test_ReturnDefinedGreeting() { … public void test_EveryGreetingReturned() { … } … } Don’t forget that Eclipse can help you get the right import statements – use Organize Imports (Ctrl-Shift-O)  methods run when the test class is run  That is, a JUnit test class is a set of tests (methods) that share a (class) name CSE 331 Autumn

Does it return a random public void testDoes_getGreetingNeverReturnSomeGreeting() { int greetingCount = RandomHello.greetings.length; int count[] = new int[greetingCount]; for (int c = 0; c < greetingCount; c++) count[c] = 0; for (int i = 1; i < 100; i++) { String rs = RandomHello.getGreeting(); for (int j = 0; j < greetingCount; j++) if (rs.equals(RandomHello.greetings[j])) count[j]++; } for (int j = 0; j < greetingCount; j++) if (count[j] == 0) fail(j+"th [0-4] greeting never returned"); assertTrue(true); } Run it 100 times If even one greeting is never returned, it’s unlikely to be random (  ) CSE 331 Autumn

What about a sleazy developer? if (randomGenerator.nextInt(2) == 0) { return(greetings[0]); } else return(greetings[randomGenerator.nextInt(5)]);  Flip a coin and select either a random or a specific greeting  The previous “is it random?” test will almost always pass given this implementation  But it doesn’t satisfy the specification, since it’s not a random choice CSE 331 Autumn

Instead: Use simple public void test_UniformGreetingDistribution() { // …count frequencies of messages returned, as in // …previous test (test_EveryGreetingReturned) float chiSquared = 0f; float expected = 20f; for (int i = 0; i < greetingCount; i++) chiSquared = chiSquared + ((count[i]-expected)* (count[i]-expected)) /expected; if (chiSquared > ) // df 4, pvalue.01 fail("Too much variance"); } CSE 331 Autumn

A JUnit test suite import org.junit.runner.RunWith; RandomHelloTest.class, SleazyRandomHelloTest.class }) public class AllTests { // this class remains completely // empty, being used only as a // holder for the above // annotations }  Define one suite for each program (for now)  The suite allows multiple test classes – each of which has its own set methods – to be defined and run together  Add tc.class to Suite.SuiteClasses annotation if you add a new test class named tc  So, a JUnit test suite is a set of test classes (which makes it a set of a set of test methods) CSE 331 Autumn

JUnit assertion methods  Can add a failure message: assertNull(“Ptr isn’t null", value)  expected is the oracle – remember this is the first (leftmost) param  The table above only describes when to fail – what happens if an assertion succeeds? Does the test pass? …causes the current test to fail… fail()immediately assertTrue(tst)if tst is false assertFalse(tst)if test is true assertEquals(expected, actual)if expected does not equal actual assertSame(expected, actual)if expected != actual assertNotSame(expected, actual)if oracle == actual assertNull(value)if value is not null assertNotNull(value)if value is null CSE 331 Autumn

 High-level concept: test behaviors in combination  Maybe add works when called once, but not when call twice  Maybe add works by itself, but fails (or causes a failure) after calling remove ArrayIntList : example public void testAddGet1() { ArrayIntList list = new ArrayIntList(); list.add(42); list.add(-3); list.add(15); assertEquals(42, list.get(0)); assertEquals(-3, list.get(1)); assertEquals(15, list.get(2)); public void testIsEmpty() { ArrayIntList list = new ArrayIntList(); assertTrue(list.isEmpty()); list.add(123); assertFalse(list.isEmpty()); list.remove(0); assertTrue(list.isEmpty()); } CSE 331 Autumn

A few hints: data structures  Need to pass lots of arrays? Use array literals public void exampleMethod(int[] values) {... }... exampleMethod(new int[] {1, 2, 3, 4}); exampleMethod(new int[] {5, 6, 7});  Need a quick ArrayList ? List list = Arrays.asList(7, 4, -2, 3, 9, 18);  Need a quick set, queue, etc.? Many take a list Set list = new HashSet ( Arrays.asList(7, 4, -2, 9)); CSE 331 Autumn

A few general hints  Test one thing at a time per test method  10 small tests are much better than one large test  Be stingy with assert statements  The first assert that fails stops the test – provides no information about whether a later assertion would have failed  Be stingy with logic  Avoid try/catch – if it’s supposed to throw an exception, use expected=... if not, let JUnit catch it CSE 331 Autumn

Test case dangers  Dependent test order  If running Test A before Test B gives different results from running Test B then Test A, then something is likely confusing and should be made explicit  Mutable shared state  Tests A and B both use a shared object – if A breaks the object, what happens to B? This is a form of dependent test order We will explicitly talk about invariants over data representations and testing if the invariants are ever broken CSE 331 Autumn

More JUnit (but not in detail today)  Timeouts – don’t want to wait forever for a test to complete  Testing for = ArrayIndexOutOfBoundsException.class) public void testBadIndex() { ArrayIntList list = new ArrayIntList(); list.get(4); // this should raise the exception } // and thus the test will pass  Setup [teardown] – methods to run before [after] each test case method [test class] is called CSE 331 Autumn

One view of testing Testing by itself does not improve software quality. Test results are an indicator of quality, but in and of themselves, they don't improve it. Trying to improve software quality by increasing the amount of testing is like trying to lose weight by weighing yourself more often. What you eat before you step onto the scale determines how much you will weigh, and the software development techniques you use determine how many errors testing will find. If you want to lose weight, don't buy a new scale; change your diet. If you want to improve your software, don't test more; develop better. Steven C McConnell  Code Complete: A Practical Handbook of Software Construction. ISBN:  CSE 331 Autumn

Next steps CSE 331 Autumn  Assignment 1: on the web now, due Friday 11:59PM  Section Thursday: Javadoc, JUnit and Eclipse – in your regularly scheduled rooms  Lectures: equality (W), ADTs (F & M)