由其他获取查询更改的Doctrine集合

时间:2010-12-11 19:30:39

标签: unit-testing symfony1 doctrine doctrine-query

我是symfony中单元测试的新手,我觉得非常讨厌,因为我遇到了一个问题,花了我1个小时来识别。

希望你们知道为什么会这样。

所以我正在测试我的“搜索”方法:

class TadalistTable extends Doctrine_Table
{
  public function search($query, $user_id)
  {
     $q = $this->createQuery('t')
     ->leftJoin('t.Notes n')
     ->where('n.name LIKE ?', '%'.$query.'%')
     ->andWhere('t.user_id = ?', $user_id);
     return $q->execute();
  }
}

它在我的网站上运行得非常好,但是当我像这样测试它时:

//Create two notes, one called "Test Note" and one called "Test Note2" in the same list

//Start test :
$searchTest = Doctrine_Core::getTable('Tadalist')->search('Test', $user->getId());
$searchNote2 = Doctrine_Core::getTable('Tadalist')->search('noTe2', $user->getId());

$t->is(count($searchTest), 1, 'Searching "Test" returned 1 list');
$t->is(count($searchTest[0]->Notes), 2, 'Searching "Test" returned 2 notes');
$t->is(count($searchNote2), 1, 'Searching "noTe2" returned 1 list');
$t->is(count($searchNote2[0]->Notes), 1, 'Searching "noTe2" returned 1 note');

第二次测试失败:

ok 20 - Searching Test returned 1 list
not ok 21 - Searching Test returned 2 notes
# Failed test (./test/unit/Model/TadalistTest.php at line 90)
# got: 1
# expected: 2
ok 22 - Searching noTe2 returned 1 list
ok 23 - Searching noTe2 returned 1 note

但如果我只是改变顺序:

//Create two notes, one called "Test Note" and one called "Test Note2" in the same list

$searchTest = Doctrine_Core::getTable('Tadalist')->search('Test', $user->getId());
$t->is(count($searchTest), 1, 'Searching "Test" returned 1 list');
$t->is(count($searchTest[0]->Notes), 2, 'Searching "Test" returned 2 notes');

$searchNote2 = Doctrine_Core::getTable('Tadalist')->search('noTe2', $user->getId());
$t->is(count($searchNote2), 1, 'Searching "noTe2" returned 1 list');
$t->is(count($searchNote2[0]->Notes), 1, 'Searching "noTe2" returned 1 note');

有效:

ok 13 - Searching Test returned 1 list
ok 14 - Searching Test returned 2 notes
ok 15 - Searching noTe2 returned 1 list
ok 16 - Searching noTe2 returned 1 note

调试之后,我看到在第一次查询之后,searchTest [0] - > Notes包含我创建的两个“Note”对象(名为“Test Note”和“Test Note2”),之后第二,它只包含“测试笔记”(“测试笔记2”似乎已经被第二个查询删除了。)

所以我想知道为什么它会像这样工作,如果它们是一种修复它的方法。

你们中任何人都知道这种奇怪的行为吗?

1 个答案:

答案 0 :(得分:0)

这是我的假设:在两个查询中,您都获得了相同的 Tadalist 对象(由相同的主键标识)。 Doctrine可能在两个集合中使用对同一对象的引用。第二个查询将覆盖第一个查询返回的Notes。

注意:这只是一个假设。请确认它是否确实发生。