Answer the question
In order to leave comments, you need to log in
How do you write testable code?
Essence of the question: If you do not rely on any framework, but take as a basis a simple implementation of MVC, without dependency injection.
For example, you need to test the prepareBuy method in the User model,
but when testing the method, you can see that the order->paid($userId) method is called inside,
which refers to an external source that cannot be pulled. accordingly, when testing, you need to wrap it in Mock:
class MockTest extends PHPUnit_Framework_TestCase
{
public function testUserPay()
{
$order = $this->getMock('Order', ['paid']);
$order->expects($this->once())
->method('paid')
->will($this->returnValue('ok'));
$subject = new User;
$subject->attach($order);
$this->assertEquals('ok', $subject->prepareBuy(999));
}
class User
{
protected $order = null;
public function attach(Order $order)
{
$this->order = $order;
}
public function prepareBuy($userId)
{
return $this->order->paid($userId);
}
}
class Order
{
public function paid($argument)
{
return $argument;
}
}
$user = new User()->attach(new Order);
$user->prepareBuy(999);
User::model()->prepareBuy(new Order, New Profile, $userId)
Answer the question
In order to leave comments, you need to log in
To solve this problem, they came up with Dependency Injection and the IoC container.
accordingly, when testing, you need to wrap it in Mock
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question