1

Suppose you're writing an interface that's suppose to be your public API, let's call it Session. It's implementation is called SessionImpl and it's going to be injected by your DI framework.

I'm stuck thinking about the class access for this SessionImpl class, whether it should be restricted to it's package (since the public API is the interface) but not being able to test it from a different test project, or just make it public and test it.

The third option would be testing it through it's interface by making the DI use a factory, and calling the factory from the test.

What's the correct approach to maintain a simple maintainable code?

1
  • 2
    In general, try to prevent too many empty classes. Do you really need to have a separate public API, or is it sufficient to make all non-API functions of SessionImpl private? Only create an interface class if you can forsee multiple implementations, e.g. CookieSession, DbSession, MemorySession, etc. The name SessionImpl suggests there is only one implementation, in that case just put the API and the implementation together. – EvertW Jan 28 '16 at 7:52
2

Yes, if the session implementations need to provide the exact same behavior it would make sense to only test through the implemented interface.

However, if the implementation is only used through the interface then it doesn't matter all that much that it has public methods -outside- it? Nothing or noone is supposed to access the class directly, except perhaps for your tests that is.

In .NET you can set an assembly attribute (InternalsVisibleTo) to allow access to internal members by white-listing a (testing) assembly. Something along these lines, depending on your environment, could work also.

I personally shy away from coming up with anything more complicated -or- if I need to open up a lot of stuff for testing it may be an indication another class is trying to come out, it needs refactoring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.