How to replace phpunit methods

Let's say I want to replace a method in an object that receives a database from a database with one that has pre-populated data. How can I do it?

According to https://phpunit.de/manual/current/en/test-doubles.html ...

setMethods ($ array methods) can be called in a Mock Builder object to specify methods that should be replaced with a custom double test. The behavior of other methods does not change. If you call setMethods (NULL), then no methods will be replaced.

Great. So phpunit tells me which methods I want to replace, but where can I say that I replace them?

I found this example:

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

Great, so the __destruct method is __destruct replaced. But what is it replaced by? I have no idea. Here is the source for this:

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

+5
source share
1 answer

Using a method that does nothing, but whose behavior you can configure later. Although I'm not sure that you fully understood how mocking the work is. You should not scoff at the class you are testing, you must scoff at the objects that the test class relies on. For instance:

 // 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)); } } 

Your test makes fun of the exact class you are trying to verify, which might be a mistake, as some methods may be overridden during ridicule.

+7
source

Source: https://habr.com/ru/post/1206170/


All Articles