Bibek Kr. Bazaz
Bibek Kr. Bazaz

Reputation: 535

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
}

}

Upvotes: 0

Views: 7737

Answers (3)

Highbrainer
Highbrainer

Reputation: 760

If you want to use mockito, I'd go for something like that :

@Spy
private A a;

@Test
public void test() {    
    
    //define the behaviour
    Mockito.when(a.display()).thenReturn(12);
    
    // call methodUnderTest
    int res = a.methodUnderTest();
    
    // check that you get what you want
    Assert.assertEquals(SOME_VALUE, res);
    
}

And if you don't want to use annotations, you'd initialize a like this :

A a = Mockito.spy(new A());

HTH!

Upvotes: -1

orirab
orirab

Reputation: 3333

If this is your class:

    public static class A{
        public int methodUnderTest() {
            return display();
        }

        public int display(){
            return 1;
        }
    }

then using mockito, you can do this:

        A a = spy(new A());
        when(a.display()).thenReturn(0);
        System.out.println(a.methodUnderTest()); // will print 0

Explanation:

When you mock() a class, there is no underlying instance, and all the methods you call will do nothing and return default values unless specified otherwise.

When you spy() on an instance, all calls get recorded, and forwarded to the actual instance. This means that your class behaviour will stay exactly the same unless you mock a specific call.


Having said that, a case like yours is usually a symptom that you need to split the class, and invest a bit in separating your concerns.

Upvotes: 3

Rashin
Rashin

Reputation: 796

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.

Upvotes: 1

Related Questions