2016-07-26 106 views
-1

我尝试对执行原则的控制器进行功能测试。当我执行我的测试时,它失败。但是当我在我的控制器中评论此行时:“$ products = $ em-> getRepository(”Couture \ FrontBundle \ Entity \ Produit“) - > findAll()”。 我的测试是成功的。PB功能测试symfony2控制器

这是我的控制器:

class ProductController extends Controller { 
    /** 
    * Get products 
    * @Route("/products") 
    * @Method("GET") 
    */ 
    public function getAllAction() { 

    $serialize = $this->get('jms_serializer'); 

    $em = $this->getDoctrine(); 

    $products = $em->getRepository('Couture\FrontBundle\Entity\Produit')->findAll(); 

    if (!$products) { 

     $response = new Response(json_encode(array('error' => 'Resources not found for products'))); 
     $response->headers->set('Content-Type', 'application/json'); 
     $response->setStatusCode('400'); 
     return $response; 
    } 

    $response = new Response($serialize->serialize($products, 'json')); 

    $response->headers->set('Content-Type', 'application/json'); 

    return $response; 
    } 
} 

这是我的课测试:

class ProductControllerTest extends WebTestCase { 

    public function testGetAll() { 

    $client = static::createClient(); 

    $client->request('GET', $client->getContainer()->get('router')->generate('couture_front_product_getall')); 

    $this->assertEquals(
      200, $client->getResponse()->getStatusCode() 
    ); 
    } 
} 

回答

0

当你评论说行,!$productsfalse,然后你的控制器返回效应初探对象与application/json内容类型标头。此响应被认为是成功的,因为它的状态码是200 OK。

我所看到的是这样的场景,是使用数据夹具来测试由doctrine entityManager管理的实体。

你的测试类可能看起来像这样(未测试的代码,只给你背后的想法):

class ProductControllerTest extends WebTestCase { 

public function testGetAll() { 

     $client = static::createClient(); 

     $fixtures = array('Acme\YourBundle\dataFixtures\LoadProductData'); 

     $this->loadFixtures($fixtures); 

     $uri= $this->getUrl('couture_front_product_getall'); 

     $crawler= $client->request('GET',$uri); 


     $this->assertEquals(200,$client->getResponse()->getStatusCode()); 

} 
} 

我在等待我也对专家进行干预和确认。我刚刚发现评论太短,无法分享我从社区了解和学习的内容。希望它有帮助