mvb13
mvb13

Reputation: 1594

Mockito: mock method parameter

I am using Mockito framework for testing. Now I am having the following problem.

This is the class I want to test.

@Service
public class Parent{

   @Autowired
   private Child child;

   public void setChildDetails(ChildDetails childDetails){
      childDetails.validate();
      ....
      int age = childDetails.getAge();  
   }

}

This is my test.

public class ParentTest {

    @InjectMocks
    private Parent parent;

    @Mock
    private Child child;

    @Before
    public void setup() {
        initMocks(this);
    }

    @Test
    public testParentMethod(){
         .....
    }

    @Test
    public testChildDetailsMethod(){
        ChildDetails childDetails = new ChildDetails();
        childDetails.setAge(20);
        parent.setChildDetails(childDetails); 
    }

}

Mock for Child property do its job. The problem is that I want also to mock childDetails.validate() (only this method) and to leave other methods like they were (getAge() must return 20). Can you suggest how to resolve this problem?

Upvotes: 0

Views: 4620

Answers (1)

John Snow
John Snow

Reputation: 5344

For this purpose you should use spy. Spy is a partual mock and will only mock the individual methods you tell it to. If validate() is a void method, you can use the doNothing() method for the spy. Use it as below:

   @Test
    public testChildDetailsMethod(){
       ChildDetailsSpy childSpy = spy(new ChildDetailsSpy());
       doNothing().when(childSpy).validate();
       childDetails.setAge(20);
       ...
   }

More reading about this subject can be found here.

Upvotes: 1

Related Questions