Archive for October 2009
21
Sessions I’ll Be Attending at Strange Loop
No comments · Posted by James Carr in Uncategorized
So many good sessions at Strange Loop in the upcoming days… it’s been hard to choose my schedule! Here’s what I plan to attend:
Thursday
- Better Ruby Through Functional Programming
- Tackling Concurrency With STM
- Polyglot and Polyparadigm Programming for Better Agility
I’d also recommend checking out my friend Mario’s presentation Zen Mind, Warrior Spirit: Antithetical Mindsets with Lessons for Agile Developers… I was tempted to go to it myself, but the technical side won me over.
Friday
- The Shiny New Spring Thing
- Extreme Web Productivity with Spring Roo
- Apache Cassandra: Pragmatic Consistency for Massive Scale
- The Ghost in the Virtual Machine: A Reference to References
-
Polyglot Web Development with Grails (Only because Clojure is included)
Should be an interesting two days… see you there!
No tags
21
Mockito for JVM 1.4 Released
No comments · Posted by James Carr in BDD, Java, Test Driven Development
For those of you who didn’t know, I’m currently contracted at a workplace that is still stuck using java 1.4 (I heard they might ring in 2010 by upgrading, but we’ll see). This has create a number of difficulties, chief amongst them (in my view) that I can’t use Mockito and most people use EasMock… version 1.2 (yeah, the one with that MockControl nonsense).
Not to be foiled, I used retrotranslator to translate mockito to 1.4 so I can use it for TestCases… it is now available on the Mockito project site.
This is pretty much a direct port, and I added the class MockitoTestCase which basically has all the methods you’d normally statically import off of the Mockito base class. Here’s a quick demo of usage:
public class CustomerServiceTest extends MockitoTestCase{
private CustomerDao customerDao;
private CustomerService customerService;
public void setUp(){
customerDao = (CustomerDao) mock(CustomerDao.class);
customerService = new CustomerService();
customerService.setCustomerDao(customerDao);
}
public void testShouldReturnTheNumberOfActiveAccounts() throws DataFormatException{
List customers = Arrays.asList(new Customer[]{new Customer(3), new Customer(4)});
when(customerDao.getActiveCustomers()).thenReturn(customers);
assertEquals(7, customerService.getTotalActiveAccounts());
}
public void testShouldSaveCustomerIfHeHasAccounts(){
Customer customer = (Customer) mock(Customer.class);
when(customer.getNumberOfAccounts()).thenReturn(new Integer(1));
customerService.saveCustomerWithAccounts(customer);
((CustomerDao) verify(customerDao)).save(customer);
}
}
Good Luck!
No tags
18
Fine Grained Stub Behavior With Mockito
4 Comments · Posted by James Carr in /dev/random, BDD, Mocks/Stubs/Fakes, Test Driven Development
Continuing a trend of Mockito related articles, I thought I’d blog about using another feature I recently discovered while trying to figure out how to implement fine grained behavior in mockito.
First, let me set the stage… I had a method call I was writing examples for that was a typical Castor marshal operation, which often looks something like this:
StringWriter w = new StringWriter(); marshaller.setWriter(w); marshaller.marshal(obj); channel.send(w.toString());
Yeah I know… it looks like shit. But sometimes APIs force that on you. Anyway, I wanted to write an example illustrating that the channel received a message that was the result of whatever marshaller wrote to the output stream, but this was a little difficult to do (but easy to do with hard coded subclasses and lots and lots of boilerplate code).
The answer comes with, well, the Answer interface. To illustrate this, let me set up an example. Given I have started a unit test that looks like this:
@RunWith(MockitoJUnitRunner.class)
public class MessageServiceTest {
@Mock private Marshaller marshaller;
@Mock private Channel channel;
private MessageServiceImpl messagService;
@Before
public void before(){
messagService = new MessageServiceImpl();
messagService.setChannel(channel);
messagService.setMarshaller(marshaller);
}
@Test
public void shouldWriteMarshalledDataOutToChannel(){
}
}
We want to be able to verify that the channel (which is a simple interface with a send(String arg) method) receives whatever String the marshaller wrote to the provided Writer. Now, because the writer is constructed in the class itself, it’s difficult to stub this out. So in order to make the writer have SOMETHING written to it, we set up an answer to be invoked both when marshaller.setWriter(..) and when the marshaller.marshall(..) method is called:
private class MarshalAnswer{
private Writer writer;
public Answer<Writer> respondToSetWriter(){
return new Answer<Writer>() {
public Writer answer(InvocationOnMock invocation) throws Throwable {
Writer w = (Writer) invocation.getArguments()[0];
writer = w;
return null;
}
};
}
public Answer<Object> respondToMarshall(final String writeThis){
return new Answer<Object>(){
public Object answer(InvocationOnMock invocation)
throws Throwable {
writer.write(writeThis);
return null;
}
};
}
}
Bleh… lots and lots of boilerplate code because of the interfaces, but oh well. Here’s the revised test case in action:
@RunWith(MockitoJUnitRunner.class)
public class MessageServiceTest {
@Mock private Marshaller marshaller;
@Mock private Channel channel;
private MessageServiceImpl messageService;
private Invoice invoice;
private MarshalAnswer answers;
@Before
public void before(){
messageService = new MessageServiceImpl();
messageService.setChannel(channel);
messageService.setMarshaller(marshaller);
invoice = new Invoice();
answers = new MarshalAnswer();
}
@Test
public void shouldWriteMarshalledDataOutToChannel() throws Exception{
doAnswer(answers.respondToSetWriter()).when(marshaller).setWriter(any(Writer.class));
doAnswer(answers.respondToMarshall("<someresult/>")).when(marshaller).marshal(invoice);
messageService.send(invoice);
verify(channel).send("<someresult/>");
}
...
I could have just created the respondTo methods in the TestCase itself, but I wanted to keep it separated by putting it in a helper class.
So now we run the test and we should see the following:

Fair enough… lets add the following code to the method we’re describing and rerun:
public void send(Invoice invoice) throws Exception{
StringWriter writer = new StringWriter();
marshaller.setWriter(writer);
marshaller.marshal(invoice);
channel.send(writer.getBuffer().toString());
}
We rerun and sure enough, green bar! The way it works is pretty simple… whenever setWriter gets invoked, the Answer object gets called and the argument is available within it (in this case the writer) which we can then store to use for the marshal call. When marshal gets called, our Answer we defined gets called and writes whatever we told it to.
While this does provide us with a useful tool when requiring some slightly complex behavior in our collaborator interactions (in this case, we essentially needed to capture what was passed to the writer, which was acting as a hidden output variable) I’d still recommend avoiding them when you can.
No tags
No tags
For real.
public Request handleRequest ( Request aRequest ) throws InternalError {
// Never called.
if ( 1 == 0 )
throw new InternalError();
return null;
}
Yep.
No tags
15
Code Comments: The Lowest Form of Communication
3 Comments · Posted by James Carr in Object Design, Thoughts, rants
Recently I’ve been working with lots and lots of legacy code written by lots and lots of people who have been separated by lots and lots of distance between them. As a side effect, a lot of the code has comments that either explain what is going on, rationale behind doing it, and sometimes even a comment providing an excuse or justification and suggesting a way it should be done. It had reminded me of a time on a previous team when we had a new guy with years of experience of solo coding and almost everytime he worked on something he put big huge comments all over the place along the lines of :
/* Here we are using string literals but we should really be using object references */
Which faithfully stayed there for months until someone came across it, yanked it out, and asked him to next time please discuss with us or just do it… we are sitting next to each other after all!
No tags
No tags
Never let stale code sit around on a machine for more than one day. Otherwise you’re just asking for trouble. ‘Nuff said.
No tags
-
An example of using my favorite mocking framework in scala with specs.
No tags
