views:

24

answers:

1

Is it possible to re-define specific expectations on the same instance of mock object?

Say I have this test which verifies OK:

List<String> foo = createMock(List.class);
expect(foo.get(1)).andReturn("Wibble").once();
expect(foo.size()).andReturn(1).once();
replay(foo);
System.out.println(foo.get(1));
System.out.println(foo.size());
verify(foo);

What I would then like to do is reset the mock, maintaining all of the defined expectations, but changing one of them, say:

reset(foo);
// Redefine just one of the two expectations
expect(foo.get(1)).andReturn("Wobble").once();                
System.out.println(foo.get(1));
System.out.println(foo.size());
verify(foo);

Doesn't work at the minute as foo.size is not defined after the reset call.

Must be a nice way to do this rather than rebuilding the expectations every time?

Thanks in advance

A: 

Could you write the expectations as a function and pass the expected argument as an argument? It's what I've done on previous occasions.

private List<String> setExpectations(String expectedString) {
  List<String> foo = createMock(List.class);
  expect(foo.get(0)).andReturn(expectedString).once();
  expect(foo.size()).andReturn(1).once();
  replay(foo);
  return foo;
}

Plus: return zeroth String, yes?

DoctorRuss