Tim
Tim

Reputation: 1469

How to test private methods using matlab.unittest?

I am currently implementing unit tests for a project written in object oriented Matlab.

From the design it makes sense, that I cannot access private methods of a class from the testing methods in my test class.

Is there any workaround to directly test those methods without making them public?

Upvotes: 4

Views: 1287

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

If you need to test them directly, the easiest thing to do is to make them public.

An alternative would be to make them protected, and then to have a subclass with a bunch of extra public methods that called the protected ones to test them (perhaps there could be one for each method under test, and they simply pass through the calls directly to the protected ones).

However, the premise of the question kind of goes against the idea of unit testing: you should be testing the public interface/contract that your class offers, which are just its public methods. As long as the public methods are well-tested, any private methods are just implementation details.

Another way to look at things might be that if your method really requires testing, it might be worth moving it into its own class.

Upvotes: 6

Related Questions