Reputation: 1
So my code looks something like this
class One
{
private final Two two;
public One()
{
two = new Two(this)
}
public void method1()
{
//do something
method2();
}
public void method2()
{
//do something
two.method3();
}
}
class Two
{
private final One one;
public Two(One one)
{
this.one=one;
}
public void method3()
{
//print something
}
}
Now, i'd like to mock method3() in class Two while i test method1() of class One and my Junit is like this.
private One one;
private Two two;
@Before
public void setup()
{
one = Mockito.spy(new One());
two = Mockito.spy(new Two(one));
}
@Test
pubic void testMethod1InClassOne()
{
Mockito.doNothing().when(testTwo).method3();
testOne.method1();
}
But somehow, method3() is not getting mocked and i'm still seeing the contents its printing. However, i can successfully mock method2(). maybe because method2() is directly called from method1() which is the method i am testing? Please suggest how can i mock method3.
Thanks, Meher
Upvotes: -1
Views: 1286
Reputation: 588
TL;DR Make testOne
testable by injecting testTwo
in it.
two
object seems to be the instance member of the instance of One
class. Therefore it needs to be mocked(or it's behaviour to be stubbed) to achieve your goal.
In testMethod1InClassOne
test method you did not inject mocked testTwo
object into testOne
object so even Mockito accepts the stubbing on the following line it does not replace it with actual call, as those happen on different instances. What is more, it seems objects of class One
are not testable, I would recommend you to add the following constructor to the class definition:
One(Two two) {
this.two = two;
}
And then your test might looks like this:
@Test
pubic void testMethod1InClassOne()
{
Two testTwo = Mockito.mock(Two.class);
One testOne = new One(testTwo);
Mockito.doNothing().when(testTwo).method3();
testOne.method1();
}
Upvotes: 1