silverstripe-framework/docs/en/02_Developer_Guides/06_Testing/How_Tos/02_FixtureFactories.md
Tyler Trout b7391fd34f
Update 02_FixtureFactories.md
- Removed duplicate `use SilverStripe\Core\Injector\Injector;`
- Changed $myPageObj to $MyObjectObj
2020-02-17 16:49:52 -05:00

1.5 KiB

title summary icon
How to use a FixtureFactory Provide context to your tests with database fixtures industry

How to use a FixtureFactory

The FixtureFactory is used to manually create data structures for use with tests. For more information on fixtures see the Fixtures documentation.

In this how to we'll use a FixtureFactory and a custom blue print for giving us a shortcut for creating new objects with information that we need.

use SilverStripe\Dev\SapphireTest;
use SilverStripe\Core\Injector\Injector;

class MyObjectTest extends SapphireTest 
{

    protected $factory;

    function __construct() {
        parent::__construct();

        $factory = Injector::inst()->create('FixtureFactory');

        // Defines a "blueprint" for new objects
        $factory->define('MyObject', [
            'MyProperty' => 'My Default Value'
        ]);

        $this->factory = $factory;
    }

    function testSomething() {
        $MyObjectObj = $this->factory->createObject(
            'MyObject',
            ['MyOtherProperty' => 'My Custom Value']
        );

        echo $MyObjectObj->MyProperty;
        // returns "My Default Value"

        echo $MyObjectObj->MyOtherProperty;
        // returns "My Custom Value"
    }
}

API Documentation