要回答你的第二個問題:Working Effectively with Legacy Code是你需要的東西:它介紹了幾種模式,打破依賴關係,以一個代碼測試。
關於你的第一個問題:這取決於你目前的情況。以下是深入書中所描述的幾個例子:
例1 - 提取和覆蓋呼叫
如果你有一個像(例如CLASSE不是在PHP,但你會得到的想法)
class MyClass {
int getNbEligibleItems(){
List<Item> rawItems = readInDb();
//Now count elegible ones
}
List<Item> readInDb(){
//Directly call DB and return a raw list
}
}
然後,你可以做readInDb
虛擬的,並使用一個測試模擬:
class TestableMyClass : MyClass {
override List<Item> readInDb(){
//Return a list of hard code test items
}
}
例2 - 參數化的構造
如果你有這樣的
class MyClass {
private IDbReader _reader;
MyClass(){
_reader = new DbReader();
}
int work(){
List<item> items = _reader.read();
//Work with items
}
}
類然後將有可能改變構造函數
MyClass() : this(new DbReader()){ }
MyClass(IDbReader reader){
_reader = reader;
}
因此,這將有可能嘲笑分貝測試
所以,簡而言之:有很多技術可以幫助你的情況。我們需要一些代碼才能更具體。我建議讀這本書,因爲它提供了很多答案。
只是爲了清楚起見,上面的代碼示例是用Java編寫的,而不是PHP。它在PHP中的工作方式與語法略有不同。 – bdsl