How do I write unit tests in PHP with a procedural codebase?

后端 未结 3 1813
清歌不尽
清歌不尽 2021-01-30 01:56

I\'m mostly convinced of the benefits of unit testing, and I would like to start applying the concept to a large existing codebase written in PHP. Less than 10% of this code is

3条回答
  •  北海茫月
    2021-01-30 02:32

    What unit tests do well, and what you should use them for, is when you have a piece of code that you give some number of inputs, and you expect to get some number of outputs back out. The idea being, when you add functionality later, you can run your tests and make sure it's still performing the old functionality the same way.

    So, if you have a procedural code-base, you can accomplish this calling your functions in the test methods

    require 'my-libraries.php';
    class SomeTest extends SomeBaseTestFromSomeFramework {
        public function testSetup() {
            $this->assertTrue(true);
        }
    
        public function testMyFunction() {
            $output = my_function('foo',3);
    
            $this->assertEquals('expected output',$output);
        }
    }
    

    This trick with PHP code bases is, often your library code will interfere with the running of your test framework, as your codebase and the test frameworks will have a lot of code related to setting up an application environment in a web browser (session, shared global variables, etc.). Expect to spend sometime getting to a point where you can include your library code and run a dirt simple test (the testSetup function above).

    If your code doesn't have functions, and is just a series of PHP files that output HTML pages, you're kind of out of luck. Your code can't be separated into distinct units, which means unit testing isn't going to be of much use to you. You'd be better off spending your time at the "acceptance testing" level with products like Selenium and Watir. These will let you automated a browser, and then check the pages for content as specific locations/in forms.

提交回复
热议问题