我正在Symfony(版本4.3)上创建我的第一个Web应用程序,并想对EventSubscriber的preRemove功能进行单元测试。
我有一个实体Book,该实体的书皮(.png)和书本文件(.pdf)存储在服务器上(而不是数据库中)。
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if ($entity instanceof Book)
$this->fileUploader->remove($entity->getBookDir());
}
并且我使用preRemove()函数创建了EventSubscriber,该功能可在删除图书时从服务器中删除这些文件。
<?php
// tests/EventListener/BookSubscriberTest.php
namespace App\Tests\EventListener;
use App\Entity\Book;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class BookSubscriberTest extends WebTestCase
{
public function testPreRemove()
{
echo "\nTesting BookSubscriber\n";
// loading necessary stuff
$container = $this->createClient()->getContainer();
$doctrine = $container->get('doctrine');
$repository = $doctrine->getRepository(Book::class);
$targetDir = $container->getParameter('books_directory'); // get server's upload directory
// find book, which contains the cover and the file (fields in my entity)
$book = $repository->findOneBy([
'file' => 1,
'cover' => 1,
]);
$book_dir = $targetDir . ($book->getBookDir()); // get path for the directory with book files
$this->assertTrue(file_exists($book_dir)); // first check if the directory really exsists
// remove it
$entityManager = $doctrine->getManager();
$entityManager->remove($book);
$entityManager->flush();
// if everything allright, preRemove should remove this folder
// so check it
$this->assertTrue(!file_exists($book_dir));
}
}
所以现在我想创建单元测试,但是我不知道从哪里开始。我有几个功能测试,可以创建一本带有封面和书本文件的新书,但是更容易理解该怎么做,因为您只需创建客户并提出请求即可。但是如何对该事件进行单元测试?
我认为我应该从entityManager获取一些实体,只需将其删除()并检查是否已删除文件? 如果是这样,如何从TestCase类中获取此实体?
更新:
我找到了一种使用WebTestCase类而不是TestCase的解决方案。并像上面我所述的那样,通过entityManager进行此操作。
function JSONToPDFConvertor() {
var sel = document.getElementById("yourSelect");
var text = sel.options[sel.selectedIndex].text;
var data = [];
// first row needs to be headers
data.push(["Date & Time", "Location", "Speed", "Ignition", "Odometer", "Batt(V)", "GPS"]);
// go through cells
for (var i = 0; i < myArr.Table1.length; i++) {
var rowData = {};
rowData[0] = myArr.Table1[i].datetimer;
rowData[1] = myArr.Table1[i].location;
rowData[2] = myArr.Table1[i].speed.toString();
rowData[3] = myArr.Table1[i].ignition;
rowData[4] = myArr.Table1[i].odometer.toString();
rowData[5] = myArr.Table1[i].battVolt;
rowData[6] = myArr.Table1[i].gpsStat;
data.push(rowData);
}
var table = data;
console.log(data);
var doc = new jsPDF('l', 'pt', 'letter');
doc.setFontSize(9);
$.each(table, function(i, row) {
$.each(row, function(j, cell) {
if (j == 0) {
doc.cell(1, 10, 90, 20, cell, i);
} else if (j == 1) {
doc.cell(1, 10, 450, 20, cell, i);
} else if (j == 4) {
doc.cell(1, 10, 65, 20, cell, i);
} else {
doc.cell(1, 10, 45, 20, cell, i);
}
});
});
doc.save('LocationReport_' + text + '.pdf');
}
但是似乎不是“单元测试”方式?我错了吗?)
对不起,我的英语,我不是母语人士)))