7

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

Oscar
  • 1,357
  • 2
  • 17
  • 24

2 Answers2

8

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.

bric3
  • 40,072
  • 9
  • 91
  • 111
  • I do have interfaces. I didn't know that I can mock the interfaces instead the implementation classes. Thanks! – Oscar Mar 09 '12 at 22:46
4

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).

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110