2016年3月30日 星期三

Stubs, Mocks, and Spies

stubs:
create fake object, and assume this fake object can response what information, response, make sure the main tested object can get the consistent result

mocks
same with stubs, but must be executed




 from https://danielzhangqinglong.github.io/2015/04/07/rspec-mock/

比如說, 現在要去測試一下Twitter是不是成功發了一條推文:
1
2
3
4
5
6
7
8
9
10
require 'twitter'
class TwitterEmotion
def tweet
twitter_client.update "I am very happy"
end
def twitter_client
Twitter::REST::Client .new
end
end
測試代碼:
1
2
3
4
it "should tweet successfully" do
emotion = TwitterEmotion. new
expect{ emotion.tweet }.not_to raise_error
end
但是這真的會把你的推文發生出去,還有,如果網絡環境不好或者Twitter的服務器沒有及時處理請求,那麼我這邊的測試就會跑不通,等等問題. 
正因為如此,才需要把使用Twitter服務的部分用mock代替.這樣測試就不會和Twitter進行交互了.下面是使用mock後的測試:
1
2
3
4
5
6
7
8
9
10
11
12
it "should tweet successfully" do
# mock Twitter client
twitter_client_mock = double( 'Twitter client' )
# 讓update方法可以在mock對像上調用
allow(twitter_client_mock). to receive(:update)
emotion = TwitterEmotion. new
allow(emotion). to receive(:twitter_client).and_return(twitter_client_mock)
# 如果在emotion上調用了twitter_client, 那麼就返回twitter_client_mock
expect{ emotion.tweet }.not_to raise_error
end



allow (想要替換方法的對象) . to receive (所要替換的方法) . and_return (返回值對象)


allow
(mock對象) . to receive (方法) . and_raise (異常)

沒有留言:

張貼留言