Reputation: 535
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
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
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
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