Zombies
Zombies

Reputation: 25872

How to mock a method which relies on updating mutable objects

I have a method which doesn't return a value. It instead accepts a list and modifies the members of this list. Obviously the list itself is mutable, as are its members.

EG: I want to mock this:

    void modifyRequests(List<MutableObject> requests);

Upvotes: 0

Views: 1399

Answers (3)

matt b
matt b

Reputation: 139931

If you are mocking that method, why does the code using that method need to know if the call to modifyRequests() changed anything?

In other words, you should be able to mock this method as a no-op and the code calling it should still function the same.

Otherwise, the code calling this method and the method itself are too tightly coupled.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340743

With Mockito (I guess other mocking frameworks can do this as well):

doAnswer(new Answer() {
  public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      List<MutableObject> arg = args[0];
      MutableObject obj = arg.get(0);
      //...
      return null;
  }})
.when(mock).modifyRequests();

Ugly, don't you think? I strongly recommend extracting this anonymous inner class and naming it descriptively. I recommend even stronger to refactor your code and simply return the List<MutableObject> requests (or maybe return modified copy - passing objects to be modified is a bit clumsy).

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500675

Well, various mocking frameworks do provide ways of doing this (executing custom actions which use the parameters when a method is invoked) - but I would strongly consider not using mocking. Unless you really want to validate the protocol between your class-under-test and its collaborators, you should consider writing a fake instead of a mock. Then you can make the fake behave however you like - and typically (IME) you end up with simpler test code.

It's not always appropriate, and mocking certainly has its place - but over time I've found that a well-written fake can be worth its weight in gold, particularly if it's a dependency used by many classes.

Upvotes: 5

Related Questions