With PHPUnit it's quite easy to test raw PHP code, but what about code that heavily relies on cookies? Sessions could be a good example.
Is there a method that doesn't require me to setup $_COOKIE
with data during my test? It feels like a hacky way of doing things.
PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.
You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status. The output shows that we ran 1 test, and made 3 assertions in it.
This is a common problem with code, especially lagacy PHP code. The common technique used is to further abstract the COOKIE/SESSION variables in related objects and using inversion of control technique(s) to pull those dependencies into scope.
http://martinfowler.com/articles/injection.html
Now before you execute a test you would instantiate a mock version of a Cookie/Session object and provide default data.
I imagine, the same effect can be achieved with legacy code by simply overriding the super global value before executing the test.
Cheers, Alex
I understand this is quite old, but I believe this needs to be updated as technology has improved since the original post. I was able to get sessions working with this solution using php 5.4 with phpunit 3.7:
class UserTest extends \PHPUnit_Framework_TestCase {
//....
public function __construct () {
ob_start();
}
protected function setUp() {
$this->object = new \User();
}
public function testUserLogin() {
$this->object->setUsername('test');
$this->object->setPassword('testpw');
// sets the session within:
$this->assertEquals(true, $this->object->login());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With