Skip to content

Mock methods that manipulate parameters

Recently, I’ve worked a little bit on redis cache for Imcache. I needed to mock a behavior of a method where the method manipulates given parameters e.g. change state or call another method. After a little bit of research, I’ve found out there’s a nice mockito feature that accomplishes what I want: doAnswer. Basically, doAnswer allows stubbing a void method with a generic answer. While answering the method call, you can do whatever you wish. So, here’s an example usage for void method

doAnswer(new Answer() {
  public Object answer(InvocationOnMock invocation) {
    //Get the arguments and manipulate them as you wish.
    Object[] args = invocation.getArguments();
    Mock mock = invocation.getMock();
    //This is a void method so we return null.
    return null;
 }
}).when(mock).someMethod();
Another example for a non-void method.
doAnswer(new Answer() {
  public Object answer(InvocationOnMock invocation) {
    Object[] args = invocation.getArguments();
    byte[] actualBytes = ((byte[]) args[0]);
    for (int i = offset; i < offset + length; i++) {
      actualBytes[i - offset] = bytes[i];
    }
    return length;
  }
}).when(mock).someMethod();

You can check out how I've made use of doAnswer for real at RedisStreamReaderTest.

doAnswer might come in handy whenever you need to call another method inside the void method. Method you're calling might be a dependency for your project so you may not have ability change method signature.

Stay updated!

Receive insights on tech, leadership, and growth.

2 Comments

  1. Vibhu Patel Vibhu Patel

    How do you accomplish this for non-void methods?

  2. Thanks for the comment Vibhu. I’ve updated the post to include a non-void method example.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.