Let’s assume a class is initialized with several parameters, none of which are intended to be publicly visible, either as reads or writes.
Nevertheless, when writing tests, I may need to modify some of these parameters to validate the behaviour of the class.
What is the right way to proceed in this case?
So far, in the spec file, I reopen the class to add the necessary
Good practice or not?
How are clients supposed to use the behavior that requires to change those properties? Take that answer and do the same in tests.
My understanding has always kinda been your tests should be testing the public API of the type. At least your unit tests that is. So do you really need to modify the type to expose the properties if they aren’t part of the public API in the first place versus just newing up another instance with the values you want? Or at least interacting with the public methods that change the internal state, then assert whatever public accessor you have returns the correct value. This way you can test the internal/private API w/o exposing it, which ultimately will make future refactors easier as long as your tests still pass you’re good versus needing to also update your monkeypatches.
As @Blacksmoke16 says, the proper answer is to only test your class external API. If those properties aren’t visible, why would your test care about their value, as they’re invisible to any user?
Just reopening and adding
property statements is just fine for a more pragmatic approach. Sometimes it’s easier to just mock
Time.now() than having every user of the class telling it what time it is.