問題描述
我正在嘗試使用 PHPunit 進行單元測試.
I am trying to focus a bit on unit testing using PHPunit.
我在這里找到了一個非常好的教程http://blog.nickbelhomme.com/php/phpunit-training-course-for-free_282
I have found a very good tutorial over here http://blog.nickbelhomme.com/php/phpunit-training-course-for-free_282
但是我遺漏了一些東西,我還不知道該怎么做.
But there is something I'm missing and don't yet understand how to do.
我有一個用戶模塊,用于維護有關用戶的所有信息.并且有一個函數 save 可以將用戶保存在數據庫中.所以我有一個 testFunction
I have a user module which maintains all information about users. And there is a function save which saves the user in the database. So I have a testFunction
public function testCanCreateUser()
{
$userData = array(
'userName' => 'User1',
'firstName' => 'Joey',
'lastName' => 'Hendricks',
'email' => 'Joey@hendricks.com',
'password' => 'f$tfe8F'
);
$user = new Model_User($userData);
$user->save();
}
我第一次運行測試時,這會起作用.因為數據庫是空的.但是當我第二次運行我的測試時它不會工作,因為我的系統不允許同一個用戶在數據庫中兩次.所以為了做到這一點,我必須在每次運行測試之前重新創建我的測試數據庫.這樣做的最佳方法是什么?
The first time when I will run my test this will work. Since the database is empty. But When I run my tests for the second time it won't work since my system doesn't allow the same user twice in the db. So In order to do this I have to recreate my testdatabase every time before I run my tests. What is the best way to do this?
或者這個問題可以用不同的方式解決嗎?
Or is this problem to be solved on a different way?
推薦答案
如果你想測試你的業務邏輯: Mock掉數據庫類并返回假數據
If you want to test your business logic: Mock away the Database class and return fake data
如果你想測試觸發 SQL 語句的類(恕我直言,你也可以測試它,因為我有點想知道我的代碼是否可以在后端的真實數據庫中正常工作)它會得到有點復雜,但有一些方法可以做到:
If you want to test the class that fires the SQL statements (and imho you could test that too since I kinda wanna know if my code works fine with a real db in the backend) it gets a little complicated but there are ways to do it:
在運行測試之前使用 setUp() 和 tearDown() 為您的數據獲得一致的狀態是(恕我直言)編寫數據庫驅動單元測試的好方法.不過,手動編寫大量自定義 sql 會很煩人.
Using setUp() and tearDown() to get a consistent state for your data before running your tests is (imho) a fine way to write db-driven unittests. It can get annoying to write lots of custom sql by hand though.
為了讓您的生活更輕松,您可以查看 DbUnit 擴展 看看這是否適用于您的應用程序.
To make your life a little easier you can look into the DbUnit extension and see if that works for your Application.
如果您真的想深入了解 Unittesting 數據庫交互,關于該主題的最佳讀物是(恕我直言)Sebastian Bergmanns phpqa 書.
If you really want to dive into Unittesting database interactions the best read on the subject is (imho) the chapter on db-unittesting in Sebastian Bergmanns phpqa book.
您的應用程序是否可以允許自定義數據庫名稱和所有表的自動設置,也可以使用大量測試數據設置一次數據庫并在所有測試中使用該數據.盡管一個測試不依賴于另一個測試編寫的數據,但您可以小心.
Could your application allow for a custom database name and automated setup of all tables it may also be possible to set the db up once with a lot of testdata and use that data in all your tests. You could be carefull so though that one test doesn't rely on data written by another one.
這篇關于使用數據庫進行 Phpunit 測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!