Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: populating different values on void methods

I am using Mockito for my unit tests. I need to mock a void method which populates some input. Very very naive Example:

class Something {
   AnotherThing thing = new AnotherThing();
   public int doSomething(Stuff stuff)
   {
      thing.doThing(stuff);
      if(thing.getName().equals("yes")){
        return 1;
      }
      else {
        return 2;
      }
   }
}

class AnotherThing() {
   public void doThing(Stuff stuff){
       if(stuff.getName().equals("Tom")) {
          stuff.setName("yes");
       }
       else {
          stuff.setName("no");
       }
   }
}

class Stuff()
{
   String name;
   // name getters and setters here
}

In this instance I would be trying to to mock AnotherThing to test Something.

However, I call this void method multiple times in the class I am testing. I need different " Answer"s every time I call it. What I mean is, I want to invoke the void method to do different things every time it is called.

I looked through the API and could not find a solution for this. Is this even possible with Mockito?

like image 402
Slamice Avatar asked Dec 27 '22 20:12

Slamice


1 Answers

What you need is a Mockito Answer object. This is an object that contains a wee bit of functionality that you can run when a method of a mock is called. Check out the Mockito documentation of doAnswer for more detail; but basically what you want is something like this.

  doAnswer(new Answer<Object>(){
        @Override
        public Object answer(InvocationOnMock invocation){
           Object[] arguments = invocation.getArguments();
           Stuff argument = (Stuff) arguments[0];
           if(stuff.getName().equals("Tom")) {
              stuff.setName("yes");
           }
           else {
              stuff.setName("no");
           }
           return null;
        }
     }).when(mockObject).doThing(any(Stuff.class));
like image 131
Dawood ibn Kareem Avatar answered Jan 07 '23 06:01

Dawood ibn Kareem