If (justMetYou) { crazy = true; cout << number << endl; int x = rand()%100; if (x>=50) callMe(); } class StarWars(int episode) { if (episode == 6) return.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
COMPUTER PROGRAMMING Task 1 LEVEL 6 PROGRAMMING: Be able to use a text based language like Python and JavaScript & correctly use procedures and functions.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Cs2220: Engineering Software Class 10: Generic Datatypes Fall 2010 University of Virginia David Evans.
Slides adapted from Alex Mariakakis, with material from Krysta Yousoufian, Mike Ernst, and Kellen Donohue Section 4: Graphs and Testing.
Using Eclipse. Getting Started There are three ways to create a Java project: 1:Select File > New > Project, 2 Select the arrow of the button in the upper.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
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.
Scripts and Flow Control. Scripts So far we have been entering commands directly into the command line But there is a better way Script files (and functions)
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Fall 2007CS 2251 Programming Tools Eclipse JUnit Testing make and ant.
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.
JavaScript Lesson 1 TBE 540. Prerequisites  Before beginning this lesson, the learner must be able to… Create a basic web page using a text editor and/or.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 7 Semantics Ismael: “Surely all this is not.
1 Types Object Oriented Programming Spring 2007.
Introduction to Computer Programming Error Handling.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Introduction to C++ - How C++ Evolved Most popular languages currently: COBOL, Fortran, C, C++, Java (script) C was developed in 1970s at AT&T (Richie)
MIS 3200 – Unit 6.2 Learning Objectives How to move data between pages – Using Query Strings How to control errors on web pages – Using Try-catch.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Chapter 12: Exception Handling
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
Cs2220: Engineering Software Class 8: Implementing Data Abstractions Fall 2010 University of Virginia David Evans.
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.
Putting Applets into Web Pages.  Two things are involved in the process of putting applets onto web pages ◦ The.class files of the applet ◦ The html.
Program documentation Using the Doxygen tool Program documentation1.
SENG 301 – Tutorial 1 Introduction to Eclipse, Subclipse, and JUnit Slides: Theodore D. Hellmann.
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 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
CRaSH Portal Team. 2 Agenda Introduction to CRaSH Deployment and connection Using the CRaSH command Develop the CRaSH commands yourself.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Introduction to Programming in Corvid EXSYS-Corvid is an intelligent systems programming environment General order of tasks: Enter and define Variables.
Justin Bare and Deric Pang with material from Erin Peach, Nick Carney, Vinod Rathnam, Alex Mariakakis, Krysta Yousoufian, Mike Ernst, Kellen Donohue Section.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 7: A Tale of Two Graphs (and.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
2.4 Exceptions n Detects try { //code that may raise an exception and/or set some condition if (condition) throw exceptionName; //Freq. A string } n Handles.
Section 4: Graphs and Testing
Unit Testing.
They both stop working when you open Windows!
Java Programming Fifth Edition
Logger, Assert and Invariants
SENG 301 – Tutorial 1 Introduction to Eclipse, Subclipse, and JUnit
Introduction to JUnit CS 4501 / 6501 Software Testing
CS Week 10 Jim Williams, PhD.
Teaching London Computing
Lecture 5: Code Red, Ariane 5, and Gambling
Exceptions CSCE 121 J. Michael Moore
الوحدة الرابعة البرمجة وصياغة حل المسائل البرمجة وأهميتها أهداف الدرس الأول مفهوم البرمجة. الفرق بين المبرمج ومستخدم البرنامج. الحاجة إلى البرامج.
Programming Assignment 2A
The programmer returns with 12 loaves of bread.
CSE 403 JUnit Reading: These lecture slides are copyright (C) Marty Stepp, They may not be rehosted, sold, or modified without expressed permission.
Section 5: HW6 and Interfaces
Section 4: Graphs and Testing
Scripts In Matlab.
Exceptions 25-Apr-19.
YOUR text YOUR text YOUR text YOUR text
Exceptions 22-Apr-19.
TCSS 360, Spring 2005 Lecture Notes
CS-1020 and Exception Handling
Input and Output Python3 Beginner #3.
Java Lessons Mr. Kalmes.
Exceptions 5-Jul-19.
Defensive Programming
Presentation transcript:

if (justMetYou) { crazy = true; cout << number << endl; int x = rand()%100; if (x>=50) callMe(); } class StarWars(int episode) { if (episode == 6) return Jedi; } private function bad() { break; } “Call Me Maybe” “Breaking Bad” “Star Wars: Episode VI – Return of the Jedi”

Slides by Alex Mariakakis with material from Krysta Yousoufian, Mike Ernst, Kellen Donohue Section 4: Graphs and Testing

Agenda Graphs Internal vs. external testing How to use JUnit How to use test script

Graphs A B CD E

Graphs A B CD E Nodes

Graphs A B CD E Edges

Graphs A B CD E Children of A

Graphs A B CD E Parents of D

Graphs A B CD E Path from A to C

Graphs A B CD E Shortest path from A to C?

Graphs A B CD E Shortest path from A to B?

Internal vs. External Testing Internal : JUnit o How you decide to abstract the object o Checked with implementation tests External: test script o Client expects to see concrete object o Checked with specification tests

A JUnit Test Class A method is flagged as a JUnit test methods run when JUnit runs import org.junit.*; import static org.junit.Assert.*; public class TestSuite public void TestName1() {... }

Using Assertions Verifies that a value matches expectations assertEquals(42, meaningOfLife()); assertTrue(list.isEmpty()); If the value isn’t what it should be, the test fails o Test immediately terminates o Other tests in the test class are still run as normal o Results show details of failed tests

Using JUnit Assertions AssertionCase for failure assertTrue( test ) the boolean test is false assertFalse( test ) the boolean test is true assertEquals( expected, actual ) the values are not equal assertSame( expected, actual ) the values are not the same (by ==) assertNotSame( expected, actual ) the values are the same (by ==) assertNull( value ) the given value is not null assertNotNull( value ) the given value is null And others: Each method can also be passed a string to display if it fails: assertEquals("message", expected, actual)

Checking for Exceptions Verify that a method throws an exception when it should Test passes if specified exception is thrown, fails otherwise Only time it’s OK to write a test without a form of public void testGetEmptyList() { List list = new ArrayList (); list.get(0); }

Setup and Teardown Methods to run before/after each test case method is public void name() {... public void name() {... } Methods to run once before/after the entire test class public static void name() {... public static void name() {... }

Setup and Teardown public class Example { List public void initialize() { empty = new ArrayList(); public void size() {... public void remove() {... }

Don’t Repeat Yourself Can declare fields for frequently-used values or constants oprivate static final String DEFAULT_NAME = “MickeyMouse”; oprivate static final User DEFAULT_USER = new User(“lazowska”, “Ed”, “Lazowska”); Can write helper methods, etc. oprivate void eq(RatNum ratNum, String rep) { assertEquals(rep, ratNum.toString()); } oprivate BinaryTree getTree(int[] items) { // construct BinaryTree and add each element in items }

#1: Be descriptive When a test fails, JUnit tells you: o Name of test method o Message passed into failed assertion o Expected and actual values of failed assertion The more descriptive this information is, the easier it is to diagnose failures Level of goodnessExample Good testAddDaysWithinMonth() Not so good testAddDays1(), testAddDays2() Bad test1(), test2() Overkill TestAddDaysOneDayAndThenFiveDaysStartingOn JanuaryTwentySeventhAndMakeSureItRollsBack ToJanuaryAfterRollingToFebruary()

#1: Be descriptive Take advantage of message, expected, and actual values No need to repeat expected/actual values or info in test name Use the right assert for the occasion: oassertEquals(expected, actual) instead of assertTrue(expected.equals(actual))

Let’s put it all together! public class DateTest {... // Test addDays when it causes a rollover between public void testAddDaysWrapToNextMonth() { Date actual = new Date(2050, 2, 15); actual.addDays(14); Date expected = new Date(2050, 3, 1); assertEquals("date after +14 days", expected, actual); }

public class DateTest {... // Test addDays when it causes a rollover between public void testAddDaysWrapToNextMonth() { Date actual = new Date(2050, 2, 15); actual.addDays(14); Date expected = new Date(2050, 3, 1); assertEquals("date after +14 days", expected, actual); } Let’s put it all together! Tells JUnit that this method is a test to run

public class DateTest {... // Test addDays when it causes a rollover between public void testAddDaysWrapToNextMonth() { Date actual = new Date(2050, 2, 15); actual.addDays(14); Date expected = new Date(2050, 3, 1); assertEquals("date after +14 days", expected, actual); } Let’s put it all together! Descriptive method name

public class DateTest {... // Test addDays when it causes a rollover between public void testAddDaysWrapToNextMonth() { Date actual = new Date(2050, 2, 15); actual.addDays(14); Date expected = new Date(2050, 3, 1); assertEquals("date after +14 days", expected, actual); } Let’s put it all together! Use assertion to check expected results

public class DateTest {... // Test addDays when it causes a rollover between public void testAddDaysWrapToNextMonth() { Date actual = new Date(2050, 2, 15); actual.addDays(14); Date expected = new Date(2050, 3, 1); assertEquals("date after +14 days", expected, actual); } Let’s put it all together! Message gives details about the test in case of failure

#2: Keep tests small Ideally, test one thing at a time o “Thing” usually means one method under one input condition o Not always possible – but if you test x() using y(), try to test y() in isolation in another test Low-granularity tests help you isolate bugs o Tell you exactly what failed and what didn’t Only a few (likely one) assert statements per test o Test halts after first failed assertion o Don’t know whether later assertions would have failed

#3: Be thorough Consider each equivalence class o Items in a collection: none, one, many Consider common input categories oMath.abs() : negative, zero, positive values Consider boundary cases o Inputs on the boundary between equivalence classes oPerson.isMinor() : age 18 Consider edge cases o -1, 0, 1, empty list, arr.length, arr.length-1 Consider error cases o Empty list, null object

Other Guidelines Test all methods o Constructors are exception to the rule Keep tests simple o Minimize if/else, loops, switch, etc. o Don’t want to debug your tests! Tests should always have at least one assert o Unless testing that an exception is thrown o Testing that an exception is not thrown is unnecessary oassertTrue(true) doesn’t count! Tests should be isolated o Not dependent on side effects of other tests o Should be able to run in any order

JUnit Summary Tests need failure atomicity so we know exactly what failed o Each test should have a descriptive name o Assertions should have clear messages to know what failed o Write many small tests, not one big test Test for expected errors / exceptions Choose a descriptive assert method, not always assertTrue Choose representative test cases from equivalent input classes Avoid complex logic in test methods if possible Use to reduce redundancy between tests

We’ve just been discussing JUnit assertions so far Java itself has assertions o However, in order to use them, you need to enable a special flag in the Java Virtual Machine (JVM) public class LitterBox { ArrayList kittens; public Kitten getKitten(int n) { assert(n >= 0); return kittens(n); } Java Asserts vs. JUnit Asserts

Enabling Java Asserts Right click the.java file you are running Go to “Run As” → “Run Configurations” Click on the “Arguments” tab Enter "-ea" under “VM arguments”

Assertions should check for things that should never happen Exceptions should check for things that might happen “Exceptions address the robustness of your code, while assertions address its correctness” Assertions vs. Exceptions public class LitterBox { ArrayList kittens; public Kitten getKitten(int n) { assert(n >= 0); return kittens(n); } public class LitterBox { ArrayList kittens; public Kitten getKitten(int n) { try { return kittens(n); } catch(Exception e) { }

Test Script Language Text file with one command listed per line First word is always the command name Remaining words are arguments Commands will correspond to methods in your code

Test Script Language # Create a graph CreateGraph graph1 # Add a pair of nodes AddNode graph1 n1 AddNode graph1 n2 # Add an edge AddEdge graph1 n1 n2 e1 # Print the nodes in the graph and the outgoing edges from n1 ListNodes graph1 ListChildren graph1 n1 n1n2

Test Script Language CreateGraph A AddNode A n1 AddNode A n2 CreateGraph B ListNodes B AddNode A n3 AddEdge A n3 n1 e31 AddNode B n1 AddNode B n2 AddEdge B n2 n1 e21 AddEdge A n1 n3 e13 AddEdge A n1 n2 e12 ListNodes A ListChildren A n1 ListChildren B n2 n1n2 n3 n1n2