·

photo credit: Memory Lane's shelf via photopin (license)

Generating dummy products for unit tests in Magento

I already wrote a number of posts about unit testing in Magento, but as with everything in Magento, some things are tricky to do, especially when it comes to unit tests.
So the other day I wrote a module that needed to do certain actions according to the value of some product attributes. Needless to say, to properly test this, I had to create some dummy products with pre-determined attributes and delete those products afterwards. In this article I’ll explain to you how I did this.

Programatically create products in Magento

So the first thing I needed to do was a way to programatically create products in Magento. The class/method I wrote to did this looks something like this:

It might look cumbersome, but what it basically does: it creates a product with some default values, just enough to be useable in Magento. The only thing you need to provide is a SKU. An optional, second parameter ($additionalData ) allows you to add extra attribute values, or overwrite some default ones. When no tax_class_id , attribute_set_id  or website_ids  are set, the method resolves them to:

  • The first tax class it can find.
  • The default attribute set.
  • All the available websites.

How to use it in your unit tests

This static class can be very easy used in your unit test to generate and delete a bunch of dummy products. Simple use the setUpBeforeClass()  and tearDownAfterClass()  methods for this:

And that’s it, with this simple ‘trick’ you can easily create dummy products prior for a test and delete them afterwards.

Visitors give this article an average rating of 4.8 out of 5.

How would you rate this article?

Leave a Reply