Why are static methods untestable? Kindly exemplify (in PHP if possible).
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Static methods themselves aren’t untestable, but if the object being tested calls a static method then a test cannot “get in between” and make it call a stub method instead. If the object being tested instead calls a regular method, the test can give it an alternative object with a stub implementation of that method.
In general, rigid dependencies are less testable while dependency injection (google it) makes code more testable.
For instance, let’s say we have a static method
getCurrentUser()that is used by the class we are testing, as followsNow
UserModel::getCurrentUser()cannot be replaced with a stub method. If we make it a regular method that we call through an object reference instead, we can pass in an alternative stub object in our test.