Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Unit) Test Driven Development

I am fairly new to TDD and not so seasoned at unit testing, hence the question. I have this legacy function written in PHP

function foo(){
   x = bar();
   y = baz();
   if (x > y)
     return 'greater';
   return 'lesser';
}

If x (value returned by bar()) is always greater than y (value returned by baz()), I will never be able to test for 'lesser' return statement.

What should I do to cover both the test cases and achieve 100% code coverage? Redefining foo() as foo(x, y) for dependency injection hooks is not an option with legacy code.

like image 679
pranay Avatar asked Nov 27 '25 00:11

pranay


1 Answers

I am assuming foo, bar and baz are all global functions. (If they are part of a class, you want to be using PHPUnit's mocking functionality).

I blogged before about how to use a pecl extension to replace a built-in function: http://darrendev.blogspot.jp/2012/07/mock-socket-in-php.html

This article shows a very interesting alternative approach using namespaces: http://marcelog.github.io/articles/php_mock_global_functions_for_unit_tests_with_phpunit.html

It appears you will need to wrap your legacy code in a file with a namespace declaration at the top. I don't know if that is a show-stopper for you or not.

like image 134
Darren Cook Avatar answered Nov 28 '25 15:11

Darren Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!