














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Exam; Class: Object-Oriented Programming and Data Structures; Subject: Computer Science; University: Cornell University; Term: Unknown 2008;
Typology: Exams
1 / 22
This page cannot be seen from the preview
Don't miss anything!















Overview
Test Driven Development
JUnit
SmallSet.java package edu.cornell.cs.cs2110; public class SmallSet { ... } SmallSetTest.java package edu.cornell.cs.cs2110; import org.junit.Test; import static org.junit.Assert.;* public class SmallSetTest { @Test public void testFoo () { SmallSet s = new SmallSet(); ... assertTrue (...); } @Test public void testBar() { ... } }
A First Test
Red Bar
SmallSet class SmallSet { public int size() { return 42; } }
Adding Items
Adding Items
Remember that Item?...
SmallSet private int _size = 0; public static final int MAX = 10; private Object _items[] = new Object[MAX]; ... public void add(Object o) { for (int i=0; i < MAX; i++) { if (_items[i] == o) { return; } } _items[_size] = o; ++_size; }
Refactoring
SmallSet (before) public void add(Object o) { for (int i=0; i < MAX; i++) { if (_items[i] == o) { return; } } _items[_size] = o; ++_size; } SmallSet (after) private boolean inSet(Object o) { for (int i=0; i < MAX; i++) { if (_items[i] == o) { return true; } } return false; } public void add(Object o) { if (!inSet(o)) { _items[_size] = o; ++_size; } }
Size Matters
SmallSet public void add(Object o) { if (!inSet(o) && _size < MAX ) { _items[_size] = o; ++_size; } } SmallSetFullException public class SmallSetFullException extends Error {}
Testing for Exceptions
SmallSetTest @Test public void testAddTooMany() { SmallSet s = new SmallSet(); for (int i=0; i < SmallSet.MAX; i++) { s.add(new Object()); } try { s.add(new Object()); fail(“SmallSetFullException expected”); } catch (SmallSetFullException e) {} }
Review
(1) add test (2) make it pass (3) refactor
Fixing a Bug