Module Development

Creating Dummy Content with SimpleTest for Drupal 7

This page is archived

We're keeping this page up as a courtesy to folks who may need to refer to old instructions. We don't plan to update this page.

Alternate resources

Sprout Video

There's another set of really useful helper methods that we haven't looked at yet which are geared towards creating dummy content for testing. Including simple tasks like generating random strings, or random names of a specified length, and more complex things like creating nodes, or even new content types. In this lesson we'll take a lot at the various helper methods in DrupalWebTestCase that assist in the creation of dummy content by creating various pieces of random content and then testing functionality based on that content.

In order to demonstrate these tools lets look at writing some tests for the core statistics module which amongst other things tracks page views for content. In order to perform these tests we're going to need a piece of content that we can view, and then view again to ensure that the statistics are properly updating.

Creating random strings can be done with DrupalWebTestCase::randomName() and DrupalWebTestCase::randomString(). Both methods take an argument that allows you to set the number of characters that should be returned, or you can just leave out to get the default. The difference between the two is that DrupalWebTestCase::randomName() will only use alphanumeric characters and the returned string will always start with a letter. This is useful for things like generating random usernames or email addresses, or other things that don't allow for special characters.

The DrupalWebTestCase::drupalCreateNode() helper can be used to create nodes. While you could navigate to and fill out the form using SimpleTest this is much quicker and requires far less code. Here's an example of creating a node:


$title = $this->randomName();
$settings = array(
 'type' => 'page',
 'promote' => 1,
 'title' => $title,
 'body' => array(LANGUAGE_NONE => array(
   array(
     'value' => 'Copy goes here',
     'format' => filter_default_format(),
   ),
 )),
);
$node = $this->drupalCreateNode($settings);

This will create a new page node with a random title and the string "Copy goes here" in the body field. The array of values passed to DrupalWebTestCase::drupalCreateNode() should mirror the structure of a node object. If you're unsure what that structure is one easy way to figure it out is to use node_load() to retrieve an existing node and inspect the returned object.

Additional resources