测试与MongoDB交互的抽象文档存储库

时间:2016-03-16 15:17:57

标签: mongodb unit-testing symfony phpunit document-repository

Heey all,

我在设置测试用例时遇到了麻烦。 我有一个简单的symfony 3项目连接到mongodb。我有多个文档,每个文档都需要一个额外的方法来查询数据库。该方法将获取插入集合中的最后一个文档,称为findLatestInserted()

此特定功能在每个文档存储库中重复。所以我决定提取它并创建一个扩展默认BaseDocumentRepository的类DocumentRepository。我的所有文档存储库仍然有自己的DocumentRepository类,例如:CpuInfoRepositoryRamInfoRepository。这些类确实提供了一些额外的方法来查询mongodb数据库和一个共同的findLatestInserted()

一切正常,但万一我想为这个方法findLatestInserted()编写一个单元测试。

我有一个名为prototyping-test的测试数据库,用于创建文档并查询它并检查结果。之后它将自行清除,因此没有文档保留。对于每个存储库,都有一个特定的URL来发布数据以在数据库中创建文件。要创建CpuInfo集合,您需要将数据发布到http://localhost:8000/ServerInfo/CreateCpuInfo。要创建RamInfo集合,您需要将数据发布到http://localhost:8000/ServerInfo/CreateRamInfo

接下来我的问题是如何编写测试来测试方法findLatestInserted()

这是我到目前为止所尝试的:

public function testFindLatestInserted()
{
    $client = self::createClient();
    $crawler = $client->request('POST',
        '/ServerInfo/CreateCpuInfo',
        [
            "hostname" => $this->hostname,
            "timestamp" => $this->timestamp,
            "cpuCores" => $this->cpuCores,
            "cpu1" => $this->cpu1,
            "cpu2" => $this->cpu2
        ]);
    $this->assertTrue($client->getResponse()->isSuccessful());

    $serializer = $this->container->get('jms_serializer');
    $cpuInfo = $serializer->deserialize($client->getResponse()->getContent(), 'AppBundle\Document\CpuInfo', 'json');

    $expected = $this->dm->getRepository("AppBundle:CpuInfo")->find($cpuInfo->getId());
    $stub = $this->getMockForAbstractClass('BaseDocumentRepository');

    $actual = $this->dm
        ->getRepository('AppBundle:CpuInfo')
        ->findLatestInserted();

    $this->assertNotNull($actual);
    $this->assertEquals($expected, $actual);
}

$actual = $this->dm->getRepository('AppBundle:CpuInfo')->findLatestInserted();行,我被困住了。因为这只会测试CpuInfo,同时还有RamInfo(以及此处未提及的其他类)。怎么会接近这个设置? 我特别希望在抽象类的级别而不是具体的类上测试方法findLatestInserted()

请帮帮我!

1 个答案:

答案 0 :(得分:1)

而不是测试整个堆栈,只需专注于在具体类中测试findLatestInserted()

将MondoDB存根注入AppBundle:CpuInfo并检查findLatestInserted()是否返回预期值。 对AppBundle:RamInfo执行相同的操作。

避免测试抽象类,总是测试具体的类。 将来,您可能决定不继承BaseDocumentRepository,也可能不会注意到findLatestInserted()的新实施失败。