在另一个类中使用的PHPUnit模拟方法 [英] PHPUnit mock method used in another class
问题描述
在另一个类中使用PHPUnit模拟方法吗? 示例:
PHPUnit mock method used in another class? Example:
class Main {
function makePayment() {
$pp = new PayPalSOAPSomeClass();
return $pp->doExpressCheckout();
}
}
在测试中,我想测试我的Main类,并模拟doExpressCheckout()方法,这是我无法测试的代码:
in testing i want test my Main class, and mock doExpressCheckout() method, my not worked code to test:
public function testStub() {
$stub = $this->getMock('PayPalSOAPSomeClass');
$stub->expects($this->any())
->method('doExpressCheckout')
->will($this->returnValue(false));
$pp = new Main;
$this->assertEquals(true, $pp->doExpressCheckout());
}
推荐答案
您在测试Main类时遇到问题.第一个问题是它在内部创建对象.您需要修改此类以使用依赖项注入.您的makePayment()应该接受PayPalSOAPSomeClass对象.
You have a problem testing the Main class. The first problem is that it creates an object internally. You need to modify this class to use dependency injection. Your makePayment() should accept a PayPalSOAPSomeClass object.
function makePayment(PayPalSOAPSomeClass $pp)
{
return $pp->doExpressCheckout();
}
在您的主类中,您可以对其进行修改以使用构造函数依赖项注入或setter依赖项注入,这比makePayment更好.然后,您引用内部对象.
In your main class, you can modify it to use a constructor dependency injection, or a setter dependency injection, which is better than the makePayment. Then, you reference the internal object.
例如:
class Main {
private $svc;
// Constructor Injection, pass the PayPalSOAPSomeClass object here
public function __construct($Service = NULL)
{
if(! is_null($Service) )
{
if($Service instanceof PayPalSOAPSomeClass)
{
$this->SetPayPalSOAP($Service);
}
}
}
function SetPayPalSOAP(PayPalSOAPSomeClass $Service)
{
$this->svc = $Service;
}
function makePayment() {
$pp = $this->svc;
return $pp->doExpressCheckout();
}
}
测试:
public function testStub()
{
$stub = $this->getMock('PayPalSOAPSomeClass');
$stub->expects($this->any())
->method('doExpressCheckout')
->will($this->returnValue(false));
$pp = new Main($stub);
$this->assertEquals(true, $pp->doExpressCheckout());
}
这篇关于在另一个类中使用的PHPUnit模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!