|
From: Steve F. <st...@m3...> - 2002-11-25 00:22:00
|
Barry Kaplan wrote:
> Seems that the dynamic mocksobjects handle this quite nicely. Here's
> what I did: The class I needed to test was an abstract class, so I could
> not use Mock or MockObject directly. Instead I mocked just the abstract
> hook methods required to the test the template methods. In the case of
> the 'getQuantity' hook method, I did:
>
> private CallSet expectedGetQuantity1 = new CallSet();
>
> // Just to provide an easier setup mechansim than having the test use
> the CallSet directly
> public void expectGetQuantity(Foo foo, Bar bar, Integer returnValue) {
> expectedGetQuantity1.expectReturn(
> new Constraint[]{P.eq(foo), P.eq(bar)}, returnValue);
> }
>
> public int getQuantity(Foo foo, Bar bar) {
> try
> return ((Integer) expectedGetQuantity1.call(new Object[]{foo,
> bar})).intValue();
> } catch (Throwable t) {
> // It kinda sucks that call() declares Throwable. Its really
> unecessary, since reflection will
> // throw the exception of the reflected. If the reflected
> method declares an exception
> // the mock method can pass it thru (or extract it from the
> exception the method.invoke() throws).
> throw new RuntimeException(t);
> }
> }
>
> public void verify() throws AssertionFailedError {
> expectedGetQuantity1.verify();
> ...
> }
For an equality test, I would have done something like:
ExpectationValue foo = new ExpectationValue("foo");
ExpectationValue bar = new ExpectationValue("bar");
int quantity;
public int getQuantity(Foo aFoo, Bar aBar) {
foo.setActual(aFoo);
bar.setActual(aBar);
return quantity;
}
public void verify() {
Verifier.verifyObject(this);
}
which I find more obvious. I might take shortcuts, like using an
ExpectationList for all the parameters and, these days, I tend not to
make the mock fields private and just call setExpected() on them
directly. If you get the names right, it's pretty readable.
S.
|