0

I am trying to use mockito to mock the return value of method3() in class3 when i run the method try() in class1 from the testclass. I have restriction as to not being able to make any edition to the codes that i have. So, i cannot add in constructors to make the mock as per some solutions that i have seen given on the internet. I am using MockMVC with WebApplicationContextSetup. Please guide me if it is possible to mock the value of method3() only using mockito and if it is not possible what is the other solution that i can use to mock the value?

class1
{
     Class2 c2 = new Class2();
     public String try()
     {
        Something temp1 = c2.method1();
     }
}

class2
{
   Class3 c3 = new Class3();
   public String method1()
   {
      return c3.method3();
   }
}
class3
{
  //Will like to mock the return value of this method
  public String method3()
  {
     return "asd";
  }
}
testclass
{
     class1 c1 = new class1();
     c1.try();
}

Thanks Alot :D

cleve yeo
  • 103
  • 2
  • 10

2 Answers2

0

Regarding your code, it looks you need to mock a static method :

return Class3.method3();

Or not

public String method3()

Please precise because the answer will be different depending your need to mock static method or not.

0

For this you need to Spy your class2.

import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import static org.junit.Assert.assertEquals;

public class TestClass {

@InjectMocks
private Class1 class1 = new Class1();

@InjectMocks @Spy
private Class2 class2 = new Class2();

@Mock
private Class3 class3;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testWithMock() {
    Mockito.when(class3.method3()).thenReturn("mocked");
    assertEquals("mocked", class1.doTry());
}

}
  • So if there are more classes in between the calls to reach class3. I must spy all those intermediate classes? – cleve yeo Dec 14 '16 at 08:44
  • Yes indeed. Usually, when you have to do such complicated things in your tests, either your are testing legacy code, either you are in specific case (it happens), either you are doing something wrong. Usually, you mock the dependencies of the system under test, but more rarely, the dependencies of the dependencies of the dependencies of the system under test. – Claude Michiels Dec 14 '16 at 13:45