benanamen Posted March 18, 2016 Share Posted March 18, 2016 As I get more into OOP it appears I should know and understand unit testing and write tests. Since everything I do is DB driven, nearly all an apps functionality requires a database. From what I read, if you are actually connecting to a DB you are not really doing unit testing, so my question is, how do you do a unit test on a method that gets its data from a DB? Here is the current class I am experimenting with. As I understand it, a unit test is for ONE method. How would I do a unit test for example on the select_user method? class User { /** * @var PDO The connection to the database */ protected $pdo; protected $row; protected $error; protected $password_hash; /** * Construct. * @param PDO $pdo The database connection */ public function __construct($pdo) { $this->pdo = $pdo; } /** * @param $request: $_POST or $_GET * @param $columns: Columns to SELECT */ public function select_user($request, $columns) { $sql = "SELECT "; foreach ($columns AS $field) { $sql .= $field . ', '; } $sql = rtrim($sql, ", "); $sql .= ' FROM users WHERE username = ?'; $stmt = $this->pdo->prepare($sql); $stmt->execute(array( $request )); $row = $stmt->fetch(PDO::FETCH_ASSOC); // No match, Do stuff. if (!$stmt->rowCount()) { $this->error['username'] = 'Bad User Name'; } else { $this->username = $row['username']; $this->password_hash = $row['password']; } } // End function select_user public function verify_password($password) { if (isset($this->password_hash)) { if (password_verify($password, $this->password_hash)) { echo 'Valid User'; // Set $_SESSION['logged_in']; } else { $this->error['password'] = 'Bad Password'; } } } public function check_errors() { if (count($this->error) > 0) { echo 'Errors<br>'; echo $error = implode("<br >\n", $this->error) . "\n"; die; } } // End function check_errors } // End Class User Quote Link to comment https://forums.phpfreaks.com/topic/301032-unit-testing/ Share on other sites More sharing options...
Jacques1 Posted March 18, 2016 Share Posted March 18, 2016 From what I read, if you are actually connecting to a DB you are not really doing unit testing, so my question is, how do you do a unit test on a method that gets its data from a DB? By using a mock object instead of an actual PDO instance. But before jumping to advanced unit tests, I'd start with the basics (i. e. writing tests for a class without dependencies). Quote Link to comment https://forums.phpfreaks.com/topic/301032-unit-testing/#findComment-1532154 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.