Core understanding of assertion testing functions in Drupal

If you need to write Simpletest test classes for your module, this article can help you.

First of all, when I began to learn the Web testing with drupal Simpletest module, I didn't know the very interesting thing: almost every assertion is implemented by $this->xpath method!
Indeed, you can check the full list of available testing functions with their code here:
If you check any code for the assert* function, you will notice it is using the xpath method. What does that mean? It means, that we can write our custom assertions! We should only just know, what the xpath is. :-D

You can read about the xpath here:
And after that you can check how to use it in drupal on the concrete examples here:!simpletest!drupal_web_test_cas...

With xpath method you can find ANY element on your page and get all of its attributes etc., just like you did it in jQuery - very usefull, isn't it?

The second great understanding was the Perl patterns. In the first time I was affraid that it will be difficult to learn it, but appeared that it is just the same regular expressions patterns form php, javascript or any other languages. So, it is just the RegEx, not the creepy 'Perl pattern'. Here is it's description if you forgot how to use the RegEx functions:
Ok, now we can assert any code on our testing page with the regular expressions, using the $this->assertPattern method.
You can check the description of this method here:
And you can check the examples how to use it here:

Knowing this two function you can assert any piece of code on your generated testing page. For example, I wrote a helper function to assert a link not from the whole page, but only inside a div with a certain class:

  protected function assertLinkIn($div_class, $label, $index = 0, $message = '', $group = 'Other') {
    $links = $this->xpath('//div[@class=:div_class]//a[normalize-space(text())=:label]', array(':div_class' => $div_class,':label' => $label));
    $message = ($message ? $message : t('Link with label %label found.', array('%label' => $label)));
    return $this->assert(isset($links [$index]), $message, $group);

It is just modernized version of the standard assertText method's code.

Now you know how to assert the code on the page, you can check other drupal functions which helps us to write complex test functions:
For example, I often use the drupalCreateNode, drupalCreateUser, login functions and so on.

Here is the interesting way to debug your testing functions: file_put_contents('output.html', $this->drupalGetContent()); (see more
And here is the way how to run them from the command line: sudo drush test-run NameOfYourTestClass --uri=http://your-local-url/

Good luck!

Drupal 7


Add new comment