1

大家好,

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

此特定功能在每个文档存储库中都有重复。所以我决定提取它并创建一个BaseDocumentRepository扩展 default的类DocumentRepository。我所有的文档存储库仍然有自己的 DocumentRepository 类,比如说:CpuInfoRepository, RamInfoRepository. 这些类确实提供了一些额外的方法来查询 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();我被卡住了。因为这只会在有 RamInfo 的情况下测试 CpuInfo(以及此处未提及的其他一些类)。如何处理这个设置?我特别想findLatestInserted()在抽象类而不是具体类的级别上测试方法。

请帮帮我!

4

1 回答 1

1

与其测试整个堆栈,不如专注findLatestInserted()于具体类的测试。

将 MondoDB 存根注入AppBundle:CpuInfo并检查是否findLatestInserted()返回预期值。对 做同样的事情AppBundle:RamInfo

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

于 2016-03-22T15:16:51.347 回答