6 ms·
The right answer to almost any question that's worth asking is "it depends". In the case of testing private methods it's no different. For example, testing pri
by asimpletune 5y ago
The right answer to almost any question that's worth asking is "it depends".
In the case of testing private methods it's no different. For example, testing private methods can lead to code having to be refactored every time you change something. This is bad, especially when presumably those methods are utilized by going through the public interface, which conveniently shouldn't change a lot.
However, it also depends on how the code is structured. Maybe it's a large systems project where there are huge private libraries that let you do important stuff. Obviously that needs to be tested. Or maybe you have an abstraction for dependencies that need to be injected at runtime to do real work, but you have a private implementation that's not exposed publicly. Even in that case, for example, it really depends.
So, it depends, and it probably depends on what do you get for doing things a certain way vs another. I'm going to say most of the time "no", but it's definitely not a rule.
- freetime2 5y agoExactly - we shouldn’t be overly concerned with whether the method is public or private. Instead we should be concerned with things like: Are these tests going fail any time someone makes the slightest change to the implementation? Do these tests require a ridiculous amount of setup? Are these tests going to run so slowly that they adversely impact the velocity of the entire team? I agree that as a general rule it’s preferable not to test private methods directly. But if testing a private method is demonstrably more efficient than getting at it through public methods, and the tests don’t end up being too brittle, then that’s probably what you should do. You could also take a look at refactoring the code to make it easier to test - but again only if that actually improves things.
- withinboredom 5y agoI look at it like this: what are the inputs/outputs of what I’m testing? Is it calling another library to do work, spy on that. Is making side-effects in the system, watch that. The only time I’d use internal/private methods directly in a test is when setting up to use the public methods would be tremendous (imagine configuring a database driver to fail in a certain way, for example). Most of the time, I see private methods being tested when the library is “in the middle” of other libraries, or is not properly abstracted.
- deleted 5y ago[deleted]