How can I unit test a Symfony2 controller?

前端 未结 4 954
暖寄归人
暖寄归人 2021-01-31 16:42

I want to use Test Driven Development as much as possible — it\'s a great way of working.

I am troubled by the fact that Symfony2 controllers create and return a new

4条回答
  •  孤街浪徒
    2021-01-31 17:35

    Use mocks to isolate models and other objects from main controller method's logic, see http://www.phpunit.de/manual/3.7/en/test-doubles.html#test-doubles.mock-objects

    I think that in older versions you could mock entire class, but with latest phpunit 3.6.10 that i have it doesn't seem to work. So i guess you are left with depency injection pattern

    class objss{
        function ss(){
            $x = new zz();
            var_dump($x->z());
        }
    }
    
    
    
    class MoTest extends PHPUnit_Framework_TestCase{
        public function setUp(){
    
        }
    
        public function testA(){
            $class = $this->getMock('zzMock', array('z'), array(), 'zz');
            $class->expects($this->any())->method('z')->will($this->returnValue('2'));
    
            $obj = new objss();
            $this->assertEquals('2', $obj->ss());
        }
    }
    

提交回复
热议问题