2014-11-04 11 views
5

के साथ विधियों को प्रतिस्थापित करने का तरीका कहें कि मैं किसी ऑब्जेक्ट में किसी विधि को प्रतिस्थापित करना चाहता हूं जो किसी डेटाबेस से डेटाबेस प्राप्त करता है जिसमें डेटा पूर्व-जनसंख्या है। यह मैं कैसे करूंगा?phpunit

https://phpunit.de/manual/current/en/test-doubles.html के अनुसार ...

setMethods (सरणी $ विधि) को नकली बिल्डर वस्तु पर कहा जा सकता है तरीकों कि एक विन्यास परीक्षण डबल के साथ प्रतिस्थापित किया जाना है निर्दिष्ट करें। अन्य तरीकों का व्यवहार नहीं बदला गया है। यदि आप setMethods (NULL) पर कॉल करते हैं, तो कोई विधि प्रतिस्थापित नहीं की जाएगी।

ग्रेट। तो यह phpunit बताता है कि मैं किस तरीके को प्रतिस्थापित करना चाहता हूं लेकिन मैं कहां कहूं कि मैं उन्हें किस जगह बदल रहा हूं?

मैं इस उदाहरण पाया:

protected function createSSHMock() 
{ 
    return $this->getMockBuilder('Net_SSH2') 
     ->disableOriginalConstructor() 
     ->setMethods(array('__destruct')) 
     ->getMock(); 
} 

महान - तो __destruct विधि बदला जा रहा है। लेकिन इसके साथ क्या बदला जा रहा है? मुझे पता नहीं है। एक विधि है कि कुछ भी नहीं है, लेकिन जिसका व्यवहार आप बाद में कॉन्फ़िगर कर सकते हैं के साथ

https://github.com/phpseclib/phpseclib/blob/master/tests/Unit/Net/SSH2Test.php

+0

क्या आप उदाहरण 9.2 देख सकते हैं? https://phpunit.de/manual/current/en/test-doubles.html मेरा मतलब है "स्टब को कॉन्फ़िगर करें" –

उत्तर

7

: यहाँ उस के लिए स्रोत है। हालांकि मुझे यकीन नहीं है कि आप पूरी तरह से समझते हैं कि नकली काम कैसे करता है। आपको उस कक्षा का मज़ाक उड़ाया नहीं जाना चाहिए जिस पर आप परीक्षण कर रहे हैं, आपको उन वस्तुओं पर नकल करना चाहिए जिन पर कक्षा का परीक्षण किया जा रहा है। उदाहरण के लिए:

// class I want to test 
class TaxCalculator 
{ 
    public function calculateSalesTax(Product $product) 
    { 
     $price = $product->getPrice(); 
     return $price/5; // whatever calculation 
    } 
} 

// class I need to mock for testing purposes 
class Product 
{ 
    public function getPrice() 
    { 
     // connect to the database, read the product and return the price 
    } 
} 

// test 
class TaxCalculatorTest extends \PHPUnit_Framework_TestCase 
{ 
    public function testCalculateSalesTax() 
    { 
     // since I want to test the logic inside the calculateSalesTax method 
     // I mock a product and configure the methods to return some predefined 
     // values that will allow me to check that everything is okay 
     $mock = $this->getMock('Product'); 
     $mock->method('getPrice') 
      ->willReturn(10); 

     $taxCalculator = new TaxCalculator(); 

     $this->assertEquals(2, $taxCalculator->calculateSalesTax($mock)); 
    } 
} 

आपका परीक्षण सटीक वर्ग आप परीक्षण करने के लिए, एक गलती हो सकती है जो, के बाद से कुछ तरीकों मजाक दौरान अधिरोहित जा सकता है की कोशिश कर रहे मजाक उड़ाता है।

 संबंधित मुद्दे