K
K
kaxa32012020-04-15 18:59:35
PHP
kaxa3201, 2020-04-15 18:59:35

How to lock phpunit method?

They write a phpunit test.
I want to make sure that delete returns exactly what I need. But in the delete method, another private method (canDelete) is called, how do I properly write a mock for canDelete ?
$data = $service->delete($params);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Fedorov, 2020-04-15
@kaxa3201

You probably don't need this, since private methods don't need to be mocked in general. Mock methods of EXTERNAL dependencies
But if you directly need it, then you also create the current object (whose method you are testing) through a mock builder. That is, the class under test becomes a mock. And you make the method under test an exception, that is, you don’t need to mock it at the mock and it will work as it is ...
Example (do not forget about the AAA methodology):

// Arrange
$provider = $this
     ->getMockBuilder(UserProvider::class)
     ->setMethodsExcept(['delete']) // перечисленные тут методы будут настоящими, хоть и мок
     ->setConstructorArgs([])       // сюда зависимости конструктора передать
     ->getMock();
$provider = $provider
     ->expects($this->once())
     ->method('canDelete') // мокаем приватный метод
     ->willReturn(true);

// Action
$result = $provider->delete();

// Assert
$this->assertEquals(true, $result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question