问题
I want to test my application with PHPUnit. So I have my application-classes and a second tree with test-classes as usual. Now I need for some test a kind of Dummy/Mock-Objects and I want to know where I should place them. Is it a different usecase and it should be place in common lib folder or what is to prefer?
回答1:
In the cases where I don't use mock objects but instead create a throw-away subclass for the test case, I name the class with the test case's prefix and place it in the same file after the test case itself.
The test case prefix avoids any chance that the class's name will clash with any real classes, and placing the code in the same file makes it easy to work with the test. If you find that you need to create multiple subclasses for one test case, this is probably a signal that your class does too much.
class MyClassTest extends PHPUnit_Framework_TestCase
{
function setUp() {
$this->fixture = new MyClassTest_DoesNothing;
}
}
class MyClassTest_DoesNothing extends MyClass
{
...
}
回答2:
I like to mirror the file structure of the project I am working on.
/project
app/
app/models/BankAccount.php
tests/
suite/
app
app/models/BankAcountTest.php
mocks
app/
app/models/BankAccountMock.php
I find doing it this way keeps everything organized. I will put small Mocks or stubs in the Test Case File if I don't intend to reuse them. As was stated in the other comments, most Mocks can be generated by PHPUnit, but sometimes it is easier just to roll your own.
回答3:
There is no suggested place for where to place hardcoded stubs or mocks. I tend to add a folder _files
whenever I feel the need for specific external resources in the same folder as the test that needs those. But that just me.
However, PHPUnit has a built-in mocking framework, so in general you dont need to hardcode your Stubs and/or Mocks. See the
- chapter on Test Doubles in the PHPUnit Manual.
Example 10.2: Stubbing a method call to return a fixed value
class StubTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
// Create a stub for the SomeClass class.
$stub = $this->getMock('SomeClass');
// Configure the stub.
$stub->expects($this->any())
->method('doSomething')
->will($this->returnValue('foo'));
// Calling $stub->doSomething() will now return
// 'foo'.
$this->assertEquals('foo', $stub->doSomething());
}
}
An alternative to PHPUnit's Mocking framework would be Pádraic Brady's Mockery, which is inspired by Ruby's flexmock and Java's Mockito
来源:https://stackoverflow.com/questions/5700009/whats-the-right-place-for-testhelper-classes-phpunit-best-practise