CS173: Intro to Computer Science - Testing
Activity Goals
The goals of this activity are:- To be able to design test cases for unit testing a program
- To design code modules for unit testing
The Activity
Directions
Consider the activity models and answer the questions provided. First reflect on these questions on your own briefly, before discussing and comparing your thoughts with your group. Appoint one member of your group to discuss your findings with the class, and the rest of the group should help that member prepare their response. Answer each question individually from the activity on the Class Activity Questions discussion board. After class, think about the questions in the reflective prompt and respond to those individually in your notebook. Report out on areas of disagreement or items for which you and your group identified alternative approaches. Write down and report out questions you encountered along the way for group discussion.Model 1: Choosing Unit Tests
1 2 3 4 5 6 7 8 9 10 11 | public class Main { public static int triangleArea( int base, int height) { // Broken Code! return 1 / 2 * base * height; } public static void main(String[] args) { System.out.println(triangleArea(5, 2)); System.out.println(triangleArea(3, -2)); } } |
Questions
- What's wrong with this code? (there is more than one answer!)
- How many calls would you make to
triangleArea
before you decide that it is "passing?" What paramter inputs would you supply to those calls? - Visit this guide and design a unit test for
triangleArea
. You can just write the code in your notes: there is no need to compile or execute it now (we will do this in lab instead!).
Model 2: Facilitating Unit Tests
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.Random; public class Main { public static boolean isHeads() { Random rng = new Random(); // Use the random number generator (rng) // to generate a value >= 0.0 and < 1.0 double randomValue = rng.nextDouble(); boolean result = false ; if (randomValue > 0.5) { result = true ; } return result; } public static void main(String[] args) { System.out.println(isHeads()); System.out.println(isHeads()); } } |
Questions
- What makes this a difficult function to test?
- What could we do to better facilitate testing a function like this?
- Print the random number
randomValue
in theisHeads
function when you compute it. Then, callrng.setSeed(100);
right before the call torng.nextDouble()
, and try running the program again. What do you notice?