我在RPEC試圖寫測試用例一類像這樣模擬類的本地方法
class ABC
def method_1(arg)
#does something and return a value based on arg
end
def initialize
@service = method_1(arg)
end
def getSomething_1
return @service.get_seomthing_1
end
def getSomething_2
return @service.get_seomthing_2
end
end
現在我想發起@Service實例變量用嘲笑的對象,這樣我可以使用嘲笑對象返回值,我可以驗證我的單元測試。
我試圖做類似
describe ABC do
before(:each) do
myObject = double()
myObject.stub(:get_something_1).and_return("SomeValue")
ABC.any_instance.stub(:method_1).and_return(myObject)
end
it "Checks the correctness of getSomething_1 method of class ABC" do
@abc = ABC.new
@abc.getSomething_1.should eql("SomeValue")
end
end
現在,當我試圖運行測試@Service是沒有得到與我想它的對象初始化。 看起來像method_1不會被定義的行爲嘲笑。 有人可以幫助我如何分配@service與我的嘲弄的對象。
我的方法_1做的是它啓動服務客戶端和service.get_seomthing_1是服務的API調用,所以我試圖切斷網絡依賴關係並使用我的模擬對象啓動服務。 – manyu
您的attr_reader工作方式,我也想通過編寫一個函數來設置我的服務變量類似的方法。 但我很困惑,爲什麼存根服務工作,因爲它也會表現爲類中的本地函數調用。 – manyu