Reputation: 175
for example I have a class
class Foo {
protected $settingUsedInloadSettings;
protected $settings;
public function __construct($param) {
$this->$settingUsedInloadSettings = $param;
$this->loadSettings();
//do other initial stuff
}
protected function loadSettings() {
$this->settings['settingToFake'] = 'some data using'
. $this->$settingUsedInloadSettings
. 'and stuff from database and/or filesystem';
}
public function functionUnderTest() {
//do api-calls with $this->settings['settingToFake']
}
}
and a working test with valid data in $this->settings['settingToFake']
class FooTest extends TestCase {
public function testFunctionToTest(){
$classUnderTest = new Foo('settingUsedInloadSettings');
$actual = $classUnderTest->functionUnderTest();
$expected = ['expectedValue'];
$this->assertEquals($expected, $actual);
}
}
now I want loadSettings()
to set Invalid data to $this->settings['settingToFake']
in a second test, to get another response from the api called in functionUnderTest()
public function testFunctionToTest(){
//fake / mock / stub loadSettings() some how
$classUnderTest = new Foo('settingUsedInloadSettings');
$actual = $classUnderTest->functionUnderTest();
$expected = ['expectedValue'];
$this->assertEquals($expected, $actual);
}
How can I do this?
Upvotes: 0
Views: 39
Reputation: 1844
You can achieve that by overriding the loadSettings
method in an anonymous class in your test:
public function testFunctionToTest()
{
$classUnderTest = new class('settingUsedInloadSettings') extends Foo {
protected function loadSettings()
{
$this->settings['settingToFake'] = 'invalid value';
}
};
// ...
}
Upvotes: 1