Search code examples
javamockitojunit4

How to mock a method of a class being called inside another method that is being tested of the same class?


For Example there is a class A with two methods methodUnderTest() and display() where methodUnderTest calls the display method. While writing a junit using mockito how can I mock the display() method?

class A{
public int method methodUnderTest{
   //some code
   display();
}

public int display(){
  //some code
}

}

Solution

  • You don't need mockito for it. In the test when you create your test object you can create it by

    A underTest = new A() {
        @Override
        public int display() {
            return <expected result>
        }
    }
    
    

    In this way you can control what kind of value is returned by the display method.