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
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With