AssertThat() and Other RMock Goodies
This week we’ve been using RMock quite a bit to try and do “true” unit tests, which I have been trying to follow the 5 rules of a unit test that Michael Feathers describes:
A test is not a unit test if:
1. It talks to the database
2. It communicates across the network
3. It touches the file system
4. It can’t run correctly at the same time as any of your other unit tests
5. You have to do special things to your environment (such as editing config files) to run it.
Anyhow, recently I discovered how to do constrains in RMock and how to use assertThat to do more informative and interesting assertions. One useful feature I found was for a method where I test that it creates an instance of an object using reflection. Although I had it returning an interface, I also wanted to check to make sure that it was an instance of the actual object I was looking for.
assertThat(person, is.instanceOf(Person.class);
Another instance I found using assertThat useful was cases where I want to see that just a substring of text is present in a return value. Rather than having too fool around with the somewhat unclear and dirty
assertTrue(returnValue.indexOf("was found") > -1);
I can instead assert
assertThat(returnValue, is.containing("was found"));
which is much much more clearer.
The is attribute of RMockTestCase includes a long list of usefule features and constants that can be used in assertThat(), such as is.ANYTHING, is.eq(), is.lt(), is.gt(), is.not(), and many more I have not explored yet.
But that’s not all! Not only have these been useful with assertThat, they’ve also been very useful to use with mock objects when setting up their expectations. For example, in one case I didn’t want to test the exact value that a method call received, but rather satisfy conditions that (a) it was called with the specified classes, and (b) contained a range of values. For Example:
public void testConstraints(){
Map foo = (Map) mock(Map.class);
foo.put(null, null);
modify().args( is.instanceOf(String.class).and(is.ANYTHING),
is.instanceOf(Integer.class).and(
is.gt(5).and(
is.lt(20))));
startVerification();
foo.put("BOO", new Integer(6));
}
However, the following fails:
foo.put("BOO", new Integer(4));
I’ll write more on this later.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!







