Sample Application: Unit Testing Java
package net.unicon;
import javax.servlet.http.*;
public class Thing2 {
public int testMe(HttpServletRequest request, String name) {
try {
return Integer.parseInt((String)request.getAttribute(name));
} catch (NumberFormatException e) {
return 0;
}
}
}
package net.unicon;
import javax.servlet.http.HttpServletRequest;
class ThingTest2 extends GroovyTestCase {
void testTestMe() {
String name = "x"; //attribute name
String value = "42"; //attribute value
//This is the mock object
HttpServletRequest request = [ getAttribute : { n -> ( n == name ? value : null) } ] as HttpServletRequest;
Thing2 thing = new Thing2();
//I have a feeling there's an easier way than "Integer.parseInt"
assertEquals(Integer.parseInt(value), thing.testMe(request, name));
assertEquals(0, thing.testMe(request, "phonyname"));
}
}
Next