2016-03-16 18 views
1

Heey all,測試與MongoDB交互的抽象文檔庫

我有麻煩設置測試用例。 我有一個簡單的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

而不是測試整個堆棧,只專注於測試findLatestInserted()在具體的類。

將MondoDB存根注入AppBundle:CpuInfo並檢查findLatestInserted()是否返回期望值。 對AppBundle:RamInfo做同樣的事情。

避免測試抽象類,總是測試具體的類。 將來,您可能會決定不繼承BaseDocumentRepository,並且可能不會注意到findLatestInserted()的新實施失敗。