teaching machines

CS 245 Lecture 1 – Hi and JUnit

September 3, 2013 by . Filed under cs245, fall 2013, lectures.

Agenda

Who Are You?

Remember

What can you say about the following methods, based only their signatures? Propose a task they might accomplish.

Red-Green-Refactor

  1. 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.
  2. 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.
  3. 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

Haiku

Wrong and we don’t know.
What are we feeling right then?
We are feeling right.