CS 245 Lecture 1 – Hi and JUnit
Agenda
- introductions
- black box
- meta
- test-driven development
- JUnit
- an class for an IP address
TODO
- Watch and play along with the CS 245 Bitbucket video above.
- Find and watch a YouTube video on JUnit.
- Read the syllabus.
- Hand in at the beginning of next lecture a 1/4 sheet of paper with two questions and two observations based on your reading and watching.
Who Are You?
- Name?
- Where is home?
- Last unassigned book you read?
- If not computers, what? (Unacceptable answer: reinvent them.)
Black Box
What can you say about the following methods, based only their signatures? Propose a task they might accomplish.
public int method1(String s)
private String[] method2(String s)
public static Random method3()
public ArrayList<Integer> method4(Scanner in)
Red-Green Refactor
- Red: think about a feature of your code that you want to support. Write a test to check the correctness of this feature’s implementation. In your code, write only a method signature and possibly a return statement. Just enough to make your code compile. Your test should fail. That’s good.
- Green: fix your implementation to make the test pass, but alter no other code. You might have great ideas about how to change parts of your code, but postpone any fixes until you have all tests passing again. That way you can verify that none of your changes break stuff.
- Refactor: now that all tests are passing, you can clean up any existing code. Rename. Simplify. Factor repeated code out into a method. Keep on testing to make sure you haven’t broken anything. When you are ready to add a new feature, return to step 1.
Code
IPAddress.java
package lecture01;
public class IPAddress {
private String ip;
public IPAddress(String ip) {
this.ip = ip;
}
public String toString() {
return ip;
}
public boolean isLocal() {
return ip.startsWith("192.168.");
}
}
TestIPAddress.java
package lecture01;
import org.junit.Assert;
import org.junit.Test;
public class TestIPAddress {
@Test
public void testConstructor() {
IPAddress addy = new IPAddress("1.1.1.1");
Assert.assertEquals("toString gave incorrect ip address", "1.1.1.1", addy.toString());
}
@Test
public void testIsLocal() {
IPAddress addy = new IPAddress("1.1.1.1");
Assert.assertFalse(addy.isLocal());
addy = new IPAddress("192.168.0.1");
Assert.assertTrue(addy.isLocal());
}
}
Haiku
I wanted a dog
Dad said no and licked my face
That’ll work, I guess
Dad said no and licked my face
That’ll work, I guess