TL;博士:
有在我原來的問題某些方面說清楚我缺乏對單元測試和功能測試之間差異的理解。 (正如我寫的,我想單元測試應用程序,但同時也在談論控制器測試;這些都是通過定義進行的功能測試)。
單元測試只適用於服務而不適用於存儲庫。這些服務可以使用實體管理器的模擬。
我的應用程序的實際使用情況實際上很好地反映在how to test code that interacts with the databse上的symfony2文檔中。他們的服務測試提供這個例子:
服務類:
use Doctrine\Common\Persistence\ObjectManager;
class SalaryCalculator
{
private $entityManager;
public function __construct(ObjectManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function calculateTotalSalary($id)
{
$employeeRepository = $this->entityManager
->getRepository('AppBundle:Employee');
$employee = $employeeRepository->find($id);
return $employee->getSalary() + $employee->getBonus();
}
}
服務測試類:
namespace Tests\AppBundle\Salary;
use AppBundle\Salary\SalaryCalculator;
use AppBundle\Entity\Employee;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Persistence\ObjectManager;
class SalaryCalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testCalculateTotalSalary()
{
// First, mock the object to be used in the test
$employee = $this->getMock(Employee::class);
$employee->expects($this->once())
->method('getSalary')
->will($this->returnValue(1000));
$employee->expects($this->once())
->method('getBonus')
->will($this->returnValue(1100));
// Now, mock the repository so it returns the mock of the employee
$employeeRepository = $this
->getMockBuilder(EntityRepository::class)
->disableOriginalConstructor()
->getMock();
$employeeRepository->expects($this->once())
->method('find')
->will($this->returnValue($employee));
// Last, mock the EntityManager to return the mock of the repository
$entityManager = $this
->getMockBuilder(ObjectManager::class)
->disableOriginalConstructor()
->getMock();
$entityManager->expects($this->once())
->method('getRepository')
->will($this->returnValue($employeeRepository));
$salaryCalculator = new SalaryCalculator($entityManager);
$this->assertEquals(2100, $salaryCalculator->calculateTotalSalary(1));
}
}
對於那些類型的測試不需要測試數據庫中,只有(痛苦)的嘲諷。
由於重要的是測試業務邏輯,而不是持久層。
僅用於功能測試是有意義的有一個人應該建立和事後拆掉自己的測試數據庫,最大的問題應該是:
在做功能測試有意義嗎?
我以前認爲測試的所有東西是正確的答案;但在使用了很多舊版軟件後,本身幾乎沒有進行測試驅動開發,但我已經變得更加懶惰實用並且認爲某些功能正在運行,直到被錯誤證明爲止。
假設我有一個應用程序解析XML,創建一個對象,並將這些對象存儲到數據庫中。如果將對象存儲到數據庫的邏輯已知可以正常工作(如:公司需要數據並且至今尚未中斷),並且即使該邏輯是一大堆廢話,也沒有迫在眉睫需要測試。盡我所能確保我的XML解析器提取正確的數據。我可以從經驗中推斷出正確的數據將被存儲。
有些情況下,功能測試是非常重要的,即如果有人寫一個網上商店。在那裏,將購買物品存儲到數據庫中的業務至關重要,這裏使用整個測試數據庫進行功能測試是絕對有意義的。
我正在通過相同的問題。到目前爲止的運氣? –
@JasonSwett沒有。由於缺乏令人滿意的答案,我剛剛開始賞金。 – k0pernikus