Hi,
I am trying to learn how to write less brittle tests. The following example of test passes although I think it is rather brittle. Does anyone have any suggestions for a better test.
In the following test $arrays = $getFields->getByName(); $arrays =
array(1)
{ [0]=> array(4) {
["uid_number"]=> string(5) "10000"
["uid"]=> string(7) "bcarver"
["firstName"]=> string(4) "Bill"
["lastName"]=> string(6) "Carver" } }
The Test (getByName):
function testGetByName() {
// Wiring...
$container = new bucket_Container(new DbFactory);
// Application code...
$container->registerImplementation('IGet', 'GetFields');
$getFields = $container->get('GetFields');
$getFields->setTable('users');
$getFields->setColName('uid');
$getFields->setName('bcarver');
$expression = array('uid_number', 'uid', 'firstName', 'lastName');
$getFields->setSelectExpression($expression);
$arrays = $getFields->getByName();
$output = "";
foreach ($arrays as $array) {
foreach($array as $key => $row) {
$output .= $key . ': ' . $row . '<br />';
}
$output .= '<br />';
}
$this->assertPattern('~uid_number: 10000<br />uid: bcarver<br />firstName: Bill<br />lastName: Carver<br />*~i', $output);
}]
The Method:
function getByName() {
if (!isset($this->table) ||! isset($this->expression)) {
//TODO implement this exception into the ErrorHandler Observer
throw new Exception('Did not set table or expression. Can not Select by name until these properties are set.');
}
$fields = '';
$field_count = count($this->expression);
$i = 0;
foreach ($this->expression as $field) {
$i++;
if ($fields == '') {
$fields .= $field;
}else {
$fields .= ',' . $field;
}
}
if (empty($this->column_name) || empty($this->name)) {
$sql ="SELECT $fields FROM " . $this->table;
} else {
$sql ="SELECT $fields FROM " . $this->table . " WHERE " . $this->column_name . " = '" . $this->name . "'";
}
$stmt = $this->pdo->prepare($sql);
$filelds_and_names = array();
try {
if ($stmt->execute()){
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $result) {
$fields_and_names[] = $result;
}
return $fields_and_names;
}
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\
";
}
}
Your thoughts are appreciated