Skip to content
Advertisement

Mocking an object returned from private method in java

I have a requirement where i want to mock an object that is return from private method. I am working with junit and mockito in my project. I can not paste the actual code here but sample code will look like this. Limitation here is that the code is legacy one and I can not refactor as of now

Class to test

 public class TestService {

   public String test() {
     TestDao testDao = getDaoObject();
     int num = testDao.getData();
     if (num < 10) {
       return "hey you loose";
     } else {
       return "hey you win";
     }
   }

   private TestDao getDaoObject() {
     return new TestDao();
   }
 }

Dao Class

public class TestDao {

  public int getData() {
    return 5;
  }
}

Test class

 public class JUnitServiceTestExample {
   @Test
   public void test() {
     TestDao testDao = Mockito.mock(TestDao.class);
     TestService test = new TestService();
     when(testDao.getData()).thenReturn(20);
     assertEquals(test.test(), "hey you win");
   }
 }   

Please help

Advertisement

Answer

You could slightly modify the getDaoObject from private to package-private like below:

TestDao getDaoObject() {
   return new TestDao();
}

Then use Mockito.spy(new TestService()) to stub the getDaoObject() and return your mocked testDao.

 public class JUnitServiceTestExample {
   @Test
   public void test() {
     TestDao testDao = Mockito.mock(TestDao.class);
     TestService test = Mockito.spy(new TestService());
     when(testDao.getData()).thenReturn(20);
     doReturn(testDao).when(test).getDaoObject();

     String result = test.test();

     assertEquals("hey you win", result);
   }
 }   

And a tip for you: the correct usage of assertEquals is assertEquals(expected, actual) not assertEquals(actual, expected)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement