In the code below, how should unit tests be written? How should I mock a database? What is the point of taunting? Imagine that in the same save class we have a setDb method that introduces a database dependency.
namespace Samtt\src;
use \Resque;
class MoHandler {
public $db;
public $resque;
private function getAuthToken($input){
$arg = json_encode($input);
return `./registermo $arg`;
}
public function setDatabase(Database $db) {
$this->db = $db;
}
public function setResque($resque) {
$this->resque = $resque;
}
public function save($stackContents){
if( !is_array($stackContent) || count($stackContents) == 0 )
return false;
$this->db->query("INSERT INTO
`mo` (msisdn, operatorid, shortcodeid, text, auth_token, created_at)
VALUES (:msisdn, :operatorid, :shortcodeid, :text , :auth_token, NOW())"
);
$this->db->beginTransaction();
foreach($stackContents as $item) {
$auth_token = $this->getAuthToken($stackContents);
$this->db->bind(':msisdn', $item['msisdn']);
$this->db->bind(':operatorid', $item['operatorid']);
$this->db->bind(':shortcodeid', $item['shortcodeid']);
$this->db->bind(':text', $item['text']);
$this->db->bind(':auth_token', $auth_token);
$this->db->execute();
}
$this->db->endTransaction();
echo 'A new job stack has been inserted into database ' . PHP_EOL ;
}
public function createJobStack($input, $queue = null){
if(! is_array($input)) {
throw new \InvalidArgumentException;
}
$stack = $queue .'-jobstack';
$size = $this->getSize($stack);
if($size < Config::$minQueueSize) {
if(! Validator::validate($input, Config::$validKeys)) {
echo 'buggy MO' . PHP_EOL ;
return false;
}
$this->resque->push($stack, $input);
echo 'new item has been added to ' . $stack . PHP_EOL;
echo 'current stack size is : ' . $size . PHP_EOL;
}else {
$stackContents = [];
for($i = 1; $i <= Config::$minQueueSize; $i++){
array_push($stackContents, $this->resque->pop($stack));
}
$this->save($stackContents);
}
return true;
}
public function getSize($stack) {
return $this->resque->size($stack);
}
public function setUp() {
$this->setDatabase((new Database));
$this->setResque((new Resque));
}
public function perform(){
$this->createJobStack($this->args, $this->queue);
}
}
I edit and add the whole class. how many statements do i need?
source
share