CS 245 Lecture 1 – Hi and JUnit
Agenda
- introductions
- black boxes
- red-green-refactor
- JUnit
- course information
Who Are You?
- Name?
- What place do you call home?
- What was the last book you read that you were not assigned to read?
- What career would you pursue if computers didn’t exist? (Outlawed answer: be an inventor and invent them.)
Remember
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 void 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 lecture0903.really;
public class IPaddress {
private String ipString;
public IPaddress(String s) {
ipString = s;
}
public String toString() {
return ipString;
}
public boolean isLocal() {
return ipString.startsWith("192.168.");
// if (ipString.startsWith("192.168.")) {
// return true;
// } else {
// return false;
// }
}
}
IPaddressTest.java
package lecture0903.really;
import junit.framework.Assert;
import org.junit.Test;
public class IPaddressTest {
@Test
public void testToString() {
String expected = "192.168.1.4";
IPaddress ip = new IPaddress(expected);
String actual = ip.toString();
Assert.assertEquals("toString gave bad result", expected, actual);
}
@Test
public void testIsLocal() {
IPaddress ip = new IPaddress("192.168.1.4");
Assert.assertTrue("local ip badly reported nonlocal", ip.isLocal());
ip = new IPaddress("192.168.1.5");
Assert.assertTrue("local ip badly reported nonlocal", ip.isLocal());
}
@Test
public void testIsNotLocal() {
IPaddress ip = new IPaddress("191.168.1.4");
Assert.assertFalse("nonlocal ip badly reported local", ip.isLocal());
ip = new IPaddress("137.168.1.4");
Assert.assertFalse("nonlocal ip badly reported local", ip.isLocal());
}
}
TODO
- Read the syllabus.
- Watch some YouTube videos on JUnit.
- Turn in at the beginning of Thursday’s lecture a 1/4-sheet with two questions and two observations from your reading and watching .
Haiku
Wrong and we don’t know.
What are we feeling right then?
We are feeling right.
What are we feeling right then?
We are feeling right.