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 generic answer. While answering the method call, you can do whatever you wish. So, here’s the example usage,

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.

Be First to Comment

Leave a Reply

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