cs61b-3

Ad Hoc Testing

unstructed testing type, also called random testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class TestSort {
/** Tests the sort method of the Sort class. */
public static void testSort() {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input);
for (int i = 0; i < input.length; i += 1) {
if (!input[i].equals(expected[i])) {
System.out.println("Mismatch in position " + i + ", expected: " + expected + ", but got: " + input[i] + ".");
break;
}
}
}

public static void main(String[] args) {
testSort();
}
}

JUnit Testing

org.junit library provide number of methods

  • https://junit.org/junit4/javadoc/4.12/org/junit/package-summary.html
  • org.junit.Assert.assertArrayEquals()
  • org.junit.Assert.assertEquals()
  • org.junit.Test
    1
    2
    3
    4
    5
    6
    public static void testSort() {
    String[] input = {"i", "have", "an", "egg"};
    String[] expected = {"an", "egg", "have", "i"};
    Sort.sort(input);
    org.junit.Assert.assertArrayEquals(expected, input);
    }

enhancements

  • precede each method with @org.junit.Test
  • change each test method to be non-static
  • remove main method from test class
  • by adding import
    • import org.junit.Test; change @org.junit.Test to @Test
    • import static org.junit.Assert.*; omit org.junit.Assert. later in code

references

# java, test

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×