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

JavaScript

Dao Class

JavaScript

Test class

JavaScript

Please help

Advertisement

Answer

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

JavaScript

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

JavaScript

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