【问题标题】:Testing Abstract Document Repository which interacts with MongoDB测试与 MongoDB 交互的抽象文档存储库
【发布时间】:2016-03-16 15:17:57
【问题描述】:

大家好,

我在设置测试用例时遇到了麻烦。 我有一个简单的 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(); 线上我卡住了。因为这只会在有 RamInfo 的情况下测试 CpuInfo(以及此处未提及的其他一些类)。如何处理这个设置? 我特别想在抽象类而不是具体类的级别上测试方法findLatestInserted()

请帮帮我!

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2012-01-27
      • 2019-12-26
      • 2020-02-02
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多