比方說,你有一個簡單的類,如:測試突變和存取方法時避免重複
class Box
def initialize
@widgets = []
end
def add_widget(widget)
@widgets << widget
end
def widgets
@widgets
end
end
我會寫一個測試,看起來是這樣的:
describe Box do
describe "#initialize" do
it "creates an empty box"
Box.new.widgets.should == []
end
end
describe "#add_widget" do
it "adds a widget to the box"
widget = stub('widget')
box = Box.new
box.add_widget(widget)
box.widgets.should == [widget]
end
end
describe "#widgets" do
it "returns the list of widgets"
widget = stub('widget')
box = Box.new
box.add_widget(widget)
box.widgets.should == [widget]
end
end
end
注意如何最後兩個測試最終是相同的。我正在努力避免這些重疊的情況。我在前兩種情況下隱式測試#widgets,但我覺得應該有一個明確的測試。但是,代碼與第二種情況相同。
如果一個類有3個公共方法,那麼我會期望至少有一個測試對應每個這些方法。我錯了嗎?
UPDATE
我通過羅恩傑弗里斯其建議不要測試簡單的存取發現this article。
非常感謝,但儘管更短,#add_widget和#widgets測試用例仍然相同。 – 2012-08-16 14:08:51
@AndyWaite:我看到你現在得到了什麼,我會更新我的答案 – 2012-08-16 14:10:06
看來你的修訂版本只包含2個測試,現在第二個測試結合了#add_widget和#widgets測試。我認爲這是一個完全合理的方法,但能夠得到一些其他觀點會很好。 – 2012-08-16 15:17:11