サーチ…
symfony3での簡単なテスト
単体テスト
単体テストは、コードに構文エラーがないことを保証し、コードのロジックが期待どおりに動作するかどうかをテストするために使用されます。簡単な例:
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%
}
}
テスト/ AppBundle /電卓/ 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