How do you test PHP classes / objects?

I read on the Internet many times that when working with dependencies in PHP it is useful to use dependency injection instead of Globals, because it makes testing easier. Can someone explain how this makes testing easier? And what will I use for the test?

+4
source share
1 answer

I would suggest learning about Unit Testing and taking a look at a few tools available for PHP. I would recommend PHPUnit , but there are SimpleTest , which, as I know, people prefer.

Minimizing the amount of changeable data is just a good idea in general. As for testing, you can write unit tests that perform small atomic functions without worrying that the variables have been changed as a side effect of any other operation. If you want to check that the state of an object is a, b, or c, you know what you need to check, because you know exactly what operations can affect the state. If your condition is global, you have no idea what other actions in your application could affect it, leaving you with difficulty supporting a bunch of spaghetti.

Joshua Bloch perfectly explains this in Effective Java, paragraph 29 . I would recommend reading this, even if it does not use PHP, the concept is the same.

Regarding unit testing, I would recommend the “Pragmatic Unit Testing” published by The Pragmatic Programmers. There are versions for Java / JUnit and C # / NUnit, but the concepts are fully applicable to PHP, especially if you use PHPUnit, which follows the xUnit templates pretty closely.

+3
source

Source: https://habr.com/ru/post/1299401/


All Articles