Working Effectively with Legacy Code
programming
dev practice
Ch. 2: Working with feedback
A test is not a unit test if:
- It talks to a database.
- It communicates across a network.
- It touches the file system.
- You have to do special things to your environment to run it.
Ch. 3: Sensing and separation
Fake objects
= new Sale();
Sale sale .scan(barcode); // scan() calls Display.showLine(item)
sale
public interface Display
{
void showLine(String line);
}
public class Sale
{
private Display display;
public Sale(Display display) {
this.display = display;
}
public void scan(String barcode) {
// item = get_item(barcode);
String lineItem = item.name() + " " + item.price();
.showLine(lineItem);
display}
}
public class FakeDisplay implements Display
{
private String lastLine = "";
public void showLine(String line){
this.lastLine = line;
}
public String getLastLine(){
return lastLine;
}
}
// test
public class SaleTest extends TestCase
{
public void testDisplayAnItem() {
= new FakeDisplay();
FakeDisplay display = new Sale(display);
Sale sale .scan("1");
saleassertEquals("xxx: $1.00", display.getLastLine());
}
}
// test with Mock
public class SaleTest extends TestCase
{
public void testDisplayAnItem() {
= new MockDisplay();
MockDisplay display .setExpectation("showLine", "xxx: $1.00")
display= new Sale(display);
Sale sale .scan("1");
sale.verify();
display}
}
A seam is a place where you can alter behavior in your program without editing in that place.