Mocking PHP functions in unit tests

前端 未结 4 2304
深忆病人
深忆病人 2021-02-13 17:52

I\'m unit-testing some PHP code with SimpleTest and I\'ve run into trouble. In my tests of a database class I want to be able to set an expectation for PHPs mysql f

4条回答
  •  深忆病人
    2021-02-13 17:58

    Here is an interesting article that writes about mocking global php functions. The author proposes a very creative solution to 'Mock' (kind off) the global php functions by overwriting the methods inside the namespace of the SUT (service under test).

    Here code from an example in the blog post where the time function is mocked:

    someClass = new SomeClass;
        }
    
        /**
         * Reset custom time after test
         */
        protected function tearDown()
        {
            self::$now = null;
        }
    
        /*
         * Test cases
         */
        public function testOneHourAgoFromNoon()
        {
            self::$now = strtotime('12:00');
            $this->assertEquals('11:00', $this->someClass->oneHourAgo());
        }
        public function testOneHourAgoFromMidnight()
        {
            self::$now = strtotime('0:00');
            $this->assertEquals('23:00', $this->someClass->oneHourAgo());
        }
    }
    

    Not sure if this is a good way to do it but it surely works well and I think it is worth mentioning here. Could be some food for a discussion...

提交回复
热议问题