如何对构造函数带有一些参数的类的方法进行单元测试? [英] How to unit test the methods of a class whose constructor take some arguments?
问题描述
我有一类这样的形式:
class A{
public function __constructor(classB b , classC c){
//
}
public function getSum(var1, var2){
return var1+var2;
}
}
我的测试用例类是这样的:
My test case class is something like this:
use A;
class ATest extends PHPUnit_Framework_TestCase{
public function testGetSum{
$a = new A();
$this->assertEquals(3, $a->getSum(1,2));
}
}
但是,当我运行phpunit时,它会抛出一些错误,例如:
However when I run the phpunit, it throws some error like:
Missing argument 1 for \..\::__construct(), called in /../A.php on line 5
即使我提供了参数,它也会抛出相同的错误,但是会在不同的文件中.
说,我实例化
$a = new A(new classB(), new classC());
Even if I provide the arguments, it throws the same error but in different file.
say, I instantiate by
$a = new A(new classB(), new classC());
然后,对于classB的构造函数,我得到相同的错误(classB的构造函数与A的形式相似).
Then, I get the same error for the constructor of classB(the constructor of classB has similar form to that of A).
Missing argument 1 for \..\::__construct(), called in /../B.php on line 10
还有其他方法可以测试功能或缺少的功能.
Is there any other way, I can test the function or something which I am missing.
我不想使用模拟(getMockBuilder(),setMethods(),getMock())进行测试,因为它似乎违背了单元测试的全部目的.
I don't want to test by using mock (getMockBuilder(),setMethods(),getMock()) as it seems to defy the whole purpose of unit testing.
推荐答案
单元测试背后的基本思想是测试一个类/方法本身,而不是对该类的依赖.为了对类A
进行单元测试,您不应使用构造函数参数的真实实例,而应使用 mocks . PHPUnit
提供了一种很好的创建方式,因此:
The basic idea behind unit test it to test a class / method itself, not dependencies of this class. In order to unit test you class A
you should not use real instances of your constructor arguments but use mocks instead. PHPUnit
provides nice way to create ones, so:
use A;
class ATest extends PHPUnit_Framework_TestCase{
public function testGetSum{
$arg1Mock = $this->getMock('classB'); //use fully qualified class name
$arg2Mock = $this->getMockBuilder('classC')
->disableOriginalConstructor()
->getMock(); //use mock builder in case classC constructor requires additional arguments
$a = new A($arg1Mock, $arg2Mock);
$this->assertEquals(3, $a->getSum(1,2));
}
}
注意:如果您不会在这里使用模拟的,但是真正的classB和classC实例将不再进行单元测试-它将是功能测试
Note: If you won't be using mock's here but a real classB and classC instances it won't be unit test anymore - it will be a functional test
这篇关于如何对构造函数带有一些参数的类的方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!