I’m working on trying to add unit tests to some code in an app i’ve been building on Modx and I’ve been struggling with figuring out how to re-structure my code to be more unit testable.
Take the below extremely basic snippet that looks at a custom database table passing it
$name to see if there are any active customers existing with that are similar to that name.
I could unit test this by simply using
runSnippet('doesCustomerExisit') and having the whole snippet run, but I’d like to not depend on the database and instead mock out that query.
I was thinking I could create a class in an external file that contains some methods to handle the query and just pass back the results - but i’m not sure how to run this snippet code from within phpUnit and pass it a mocked version of the class.
// Get name from scriptProperties $name = $modx->getOption('name', $scriptProperties, null); // remove extra whitespace around the name $name = preg_replace('/\s+/', ' ', $name); $name = trim($name); // create query of Customers class $query = $modx->newQuery('Customers'); $query->select('name'); $query->where(array( 'name:LIKE' => $name, 'active' => 1 )); $count = $modx->getCount('Customers',$query); return $count == 0 ? false : true;