Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking package private classes

Using Mockito or another similar framework. Is there a way to mock a package-private class? I am trying to test my service layer mocking my DAO classes. The problem is that the DAO instances are package private and only can be obtained through a factory.

MyPackagePrivateDao mockedDao = mock(MyPackagePrivateDao.class);

The compiler says that the class cannot be accessed from outside the package. Do you have any example?

Thanks

like image 389
Oscar Avatar asked Feb 22 '23 05:02

Oscar


2 Answers

This is not possible with Mockito, it requires to modify the bytecode of the actual class. This is not a planned feature.

Don't you have interfaces that you could eventually mock for these DAOs ?

Another option is to look on PowerMock which is great to deal with legacy code, ie when the software design is forcing you to mock statics, private, final, etc.

like image 149
Brice Avatar answered Feb 28 '23 04:02

Brice


Presumably, your problem is that your SUT (and therefore its test) is in a different package from the class that you want to mock, otherwise there wouldn't be a problem.

The way I would solve this is to write a static utility method in the test class for the class that you want to mock. This utility method should just create and return a mock of the desired class, which it can do because it's in the right package. You can then call the utility method instead of calling mock(MyPackagePrivateDao.class).

like image 28
Dawood ibn Kareem Avatar answered Feb 28 '23 03:02

Dawood ibn Kareem