-1

So I have a class with 2 public methods init() and doStuff(). init() sets up a private variable $_myPrivVar. The doStuff() method uses this variable.

When writing unit tests for doStuff() what's the best practice for setting up $_myPrivVar? Presumably I don't want to use init() to do it as my unit test is suddenly testing 2 units of code?

This is a contrived version of my real world scenario.

Force Hero
  • 2,674
  • 3
  • 19
  • 35
  • 1
    Possible duplicate of [How to test a class that has private methods, fields or inner classes?](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes) – Raedwald Jan 28 '16 at 11:56
  • 1
    It depends on your definition of a unit and what it is you a *really* trying to test. If you define the unit as the class, rather than the method then there is nothing wrong with calling two methods on the same class. What happens if you call `init` on its own, what happens if you call `doStuff` on its own without having call `init` first... – forsvarir Jan 28 '16 at 12:01

1 Answers1

2

First the unit in unit test is not necessarily one method - it can be a class or whatever as well.

But more importantly: if you have a function that just depends on one argument (your $_myPrivVar) than please implement a function that takes this value as an input.

If you really make all dependencies into inputs (aka making a pure function) you will see that this one is easily testable.

You can wrap it up later if you want - but for one argument ... don't bother


the other way is to provide a public setter for this variable - most languages have compiler variables/symbol/whatever you will call it (for example C# and #if ...) you can use to even remove those setters from your release version later.

Random Dev
  • 51,810
  • 9
  • 92
  • 119