I'm working on a contrib module port to Drupal 8 and am currently adding additional test coverage (#2586125). The module provides both a field formatter and a views style plugin. I have good working test coverage for the field formatter and am now focusing on several views test cases (simpletest based on Drupal\simpletest\WebTestBase).
I have built a simple view, that uses my module's views style plugin along with a few other simple dependencies (some field storage conf, etc.), and exported this as a couple yml conf files. What's not clear to me however is the best practice way to load this bundled view during each functional test case.
A couple ideas come to mind:
Method 1: Bundle View as Config in Test Module Dependency
I Drupal 7 the standard method appeared to be to export a view and then bundle it inside a test-only module (with hook_views_default_views()) which is installed as part of the test case setup. In D8 the exported view yml can just be placed inside a test module's config/install directory and then the module made a dependency inside the $modules property of the test class.
Method 2: Add View Explicitly during Setup with ViewTestData::createTestViews()
Some of the D8 views module's own tests use Drupal\views\Tests\ViewTestData::createTestViews(), along with a $testViews property array to directly enable a specific view inside the test setup. Something like:
public static $modules = array('node', 'field', 'image', 'my_module', 'views');
// Views used by this test.
public static $testViews = array('my_test_view'); // Exported yml inside config/test_views of my_test_views_module
/**
* Define setup tasks.
*/
public function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('my_test_views_module'));
// Additional setup...
}
Other Factors
The way configuration is loaded and cached, and related dependencies are resolved during tests is slightly mysterious. I've noticed that test cases which also programmatically add configuration that a view depends on (using something like $this->drupalCreateContentType()
for a content type config or entity_create()
for field storage config) can be tricky. In these cases Method 1 could be problematic as the view may get loaded from conf before it's dependencies are programmatically prepared. This is leading me to think that Method 2 is potentially preferred, but all the factors are not yet clear.