수색…
심포니 3의 간단한 테스트
단위 테스트
단위 테스트는 코드에 구문 오류가 없는지 확인하고 예상 한대로 작동하도록 코드의 논리를 테스트하는 데 사용됩니다. 간단한 예 :
src / AppBundle / Calculator / BillCalculator.php
<?php
namespace AppBundle\Calculator;
use AppBundle\Calculator\TaxCalculator;
class BillCalculator
{
private $taxCalculator;
public function __construct(TaxCalculator $taxCalculator)
{
$this->taxCalculator = $taxCalculator;
}
public function calculate($products)
{
$totalPrice = 0;
foreach ($products as $product) {
$totalPrice += $product['price'];
}
$tax = $this->taxCalculator->calculate($totalPrice);
return $totalPrice + $tax;
}
}
src / AppBundle / Calculator / TaxCalculator.php
<?php
namespace AppBundle\Calculator;
class TaxCalculator
{
public function calculate($price)
{
return $price * 0.1; // for example the tax is 10%
}
}
tests / AppBundle / Calculator / BillCalculatorTest.php
<?php
namespace Tests\AppBundle\Calculator;
class BillCalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testCalculate()
{
$products = [
[
'name' => 'A',
'price' => 100,
],
[
'name' => 'B',
'price' => 200,
],
];
$taxCalculator = $this->getMock(\AppBundle\Calculator\TaxCalculator::class);
// I expect my BillCalculator to call $taxCalculator->calculate once
// with 300 as the parameter
$taxCalculator->expects($this->once())->method('calculate')->with(300)->willReturn(30);
$billCalculator = new BillCalculator($taxCalculator);
$price = $billCalculator->calculate($products);
$this->assertEquals(330, $price);
}
}
내 BillCalculator 클래스를 테스트 했으므로 BillCalculator가 총 제품 가격 + 10 % 세금을 반환하도록 할 수 있습니다. 단위 테스트에서는 자체 테스트 케이스를 만듭니다. 이 테스트에서는 2 가지 제품 (가격은 100과 200)을 제공하므로 세금은 10 % = 30이됩니다. TaxCalculator가 30을 반환하므로 총 가격은 300 + 30 = 330이됩니다.
기능 테스트
기능 테스트는 입력 및 출력을 테스트하는 데 사용됩니다. 주어진 입력으로, 출력을 생성하기 위해 프로세스를 테스트하지 않고 일부 출력을 기대했습니다. (단위 테스트에서는 코드 흐름을 테스트하기 때문에 단위 테스트와 다릅니다.) 간단한 예 :
namespace Tests\AppBundle;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ApplicationAvailabilityFunctionalTest extends WebTestCase
{
/**
* @dataProvider urlProvider
*/
public function testPageIsSuccessful($url)
{
$client = self::createClient();
$client->request('GET', $url);
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function urlProvider()
{
return array(
array('/'),
array('/posts'),
array('/post/fixture-post-1'),
array('/blog/category/fixture-category'),
array('/archives'),
// ...
);
}
}
필자는 내 컨트롤러를 테스트하여 컨트롤러가 주어진 URL로 400 (찾지 못함) 또는 500 (내부 서버 오류) 대신 200 응답을 반환하도록 할 수 있습니다.
참고 문헌 :
- http://symfony.com/doc/current/best_practices/tests.html
- http://symfony.com/doc/current/book/testing.html
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow