Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testable Code - small application example

Tags:

php

phpunit

I've been spending time to assimilate the methodologies behind writing testable code, and I stumbled on a great post by Misko Hevery where he explains clearly how to approach dependencies in application building, by using factories for example to load all objects and thus reduce lines of dependencies that complicate testing.

In his post he gives a minimal albeit insightful example of how he sets up application in java, shamelessly quoted below with great respect to the dude:

// Your main should look like this:
class Main {
  public static void main(String…args) {
    AppFactory factory = new AppFactory(args);
    MyApp app = factory.create();
    app.run();
    }
}

He then states:

Notice how the code is broken to three phases. Create factory, create app, run app. This makes it testable. No matter what your app, you should fallow this pattern. To got singletons to right places the Factory only creates a single instance and then passes that instance to the constructors of all classes as it calls new. See: http://misko.hevery.com/2009/03/30/collaborator-vs-the-factory/

I am not proficient in Java, but assume this can be mimicked in php, minus the main() method of course, but where would $args come from in the context of a web-app? And initialisation?

I would be very interested in seeing a minimal testable-app example in PHP, or even links to apps that one would considered test-efficient. Initialisation is what I am curious about, mostly. My purpose is not to copy-paste, but learn from what experienced OOP coders have put out.

I did rummage through the code of a few popular code libraries: Zend, Symphony but these frameworks are not runnable applications and seem "too huge too fast" for me to grasp a clear picture. Besides, some deficiencies have been pointed out in those framework regarding testing practices. Just a small example, if possible (even if not runnable) would give me a better grip on proper OOP code-layout practices when starting a small app from scratch.

like image 792
stefgosselin Avatar asked May 12 '11 08:05

stefgosselin


People also ask

What is a good testable code?

Testable code is code of high quality. It's cohesive and loosely coupled. It's well encapsulated and in charge of its own state. In short, it's singularly defined in its own proper place so that it's straightforward to maintain and extend.

Which type of test is used to test the smallest unit of code?

A unit test is a way of testing a unit - the smallest piece of code that can be logically isolated in a system. In most programming languages, that is a function, a subroutine, a method or property.


1 Answers

Sebastian Bergmann, author of PHPUnit, has a sample app to illustrate what you are asking for at GitHub:

  • https://github.com/thePHPcc/bankaccount
like image 96
Gordon Avatar answered Oct 05 '22 12:10

Gordon