theDima
theDima

Reputation: 756

Testing a unit for which a specific private method invocation is required?

I have a testing dilemma:

I'm writing a unit test for Unit A. The method I'm about to test is func(B param). In the (non testing) code the only place where the func(..) is called is in class C, it's also the only place in the project where variables of type B can be instanciated (to be sent as parameters to the func(B param), so the instanciation method is private.

Now, I'm not sure how should I create a B instance inside the Unit test. Of cause I can change private to public in a method declaration of the method which creates B, but I don't feel right about it, since it'll expose the method to the rest of the project.

I can also simply duplicate the B creation method into the Unit test class, but I hate duplicating code. Is there some known best practice for such cases?

Thanks a lot, Dima

Upvotes: 1

Views: 37

Answers (2)

GhostCat
GhostCat

Reputation: 140427

You would be looking into using a mocking framework like EasyMock or Mokito to create a "test double" object of your class B here.

Upvotes: 1

Robbie Dee
Robbie Dee

Reputation: 1977

As a rule of thumb, only public methods should be tested directly. By extension, public code should test all private code. Depending on what language you're using, you can also force less exposed code to be exposed to unit testing frameworks without having to change every method (e.g. InternalsVisibleTo in C#) but I accept that this option won't be available to all languages using all frameworks.

As well as unit testing, another tool in your armoury should be some sort of code coverage tool to ensure that as much of your code is being covered by said tests as possible.

Upvotes: 1

Related Questions