CSE 331: Software Design and Implementation, Autumn 2026
Your job is to deliver code that you know works.
Your job is to deliver code that you know works.
Definition
Code is correct if it meets its specification.
Your job is to deliver code that you know works.
Three ways to gain knowledge:
Today: testing
Definition
A test runs code on a chosen input and compares the actual behavior to the expected behavior.
A test passes when the behaviors match and fails when they don't match.
Expected behavior first
Determine the expected behavior before running the code and observing the actual behavior. (Why?)
7/**
8 * Searches for a value in part of an array.
9 *
10 * @param a the array to search; must be non-null
11 * @param lo the index where the range to search begins
12 * @param hi the index just past where the range to search ends
13 * @param x the value to search for
14 * @requires 0 <= lo <= hi <= a.length
15 * @return some index i with lo <= i < hi and a[i] == x,
16 * or -1 if there is none
17 */
18static int indexOf(int[] a, int lo, int hi, int x) {18static int indexOf(int[] a, int lo, int hi, int x) {
19 for (int i = lo; i < hi; i++) {
20 if (a[i] == x) {
21 return i;
22 }
23 }
24 return -1;
25}7/**
8 * Searches for a value in part of an array.
9 *
10 * @param a the array to search; must be non-null
11 * @param lo the index where the range to search begins
12 * @param hi the index just past where the range to search ends
13 * @param x the value to search for
14 * @requires 0 <= lo <= hi <= a.length
15 * @return some index i with lo <= i < hi and a[i] == x,
16 * or -1 if there is none
17 */
18static int indexOf(int[] a, int lo, int hi, int x) {
18static int indexOf(int[] a, int lo, int hi, int x) {
19 for (int i = lo; i < hi; i++) {
20 if (a[i] == x) {
21 return i;
22 }
23 }
24 return -1;
25}
a = {3, 0, 7}, lo = 0, hi = 3, x = 76public class IndexOfTest {
7 @Test
8 void findsTheOnlyMatch() {
9 int[] a = {3, 0, 7};
10 assertEquals(2, IndexOf.indexOf(a, 0, 3, 7));
11 }@Test: JUnit runs this method as a test
Step 1: the input you chose
Steps 2 to 4: expect 2, run the call, and compare
{5, 1, 5, 2, 5}, the whole range, x = 519@Test
20void findsTheFirstMatch() {
21 int[] a = {5, 1, 5, 2, 5};
22 assertEquals(0, IndexOf.indexOf(a, 0, 5, 5));
23}Expects 0, the first match
25@Test
26void findsSomeMatch() {
27 int[] a = {5, 1, 5, 2, 5};
28 int i = IndexOf.indexOf(a, 0, 5, 5);
29 assertTrue(0 <= i && i < 5 && a[i] == 5);
30}Checks only D's promise: in the range, and holding 5
Definition
A specification-based test checks only behavior that the specification promises, so it passes on every correct implementation.
indexOf on {2, 2}, the whole range, x = 2Your job is to deliver code that you know works.