問題描述
有人告訴我@Mock 通常只用于單元測試,但我認為它對于替換測試類之外的外部部分很有用.在集成測試中模擬是否正確?
Somebody told me @Mock is usually employed only for unit tests but I think is useful for substituting the external parts outside the tested class. Is it correct to mock in integration tests?
推薦答案
最后,這都是關于措辭的.
In the end, this is all about wording.
當您從最基本的意義上考慮正確"時,例如 正確性,那么答案很簡單:沒有.
When you think of "correct" in its very fundamental sense, as in correctness, then the answer is simply: no.
您知道,集成測試的目標是確保您的集成系統(由多個不同的組件組成)按預期運行.集成測試的目的是驗證您的組件管道"是否按預期工作.因此:當系統的部分被模擬出來時,您無法驗證您的系統是否正常工作.
You see, the goal of an integration test is to ensure that your integrated system (consisting of multiple, different components) functions as expected. The purpose of an integration test is to verify that your "plumbing" of components works as expected. Therefore: you can't verify that your system works when parts of that system are mocked out.
但是,您可以不那么嚴格地考慮正確性".
But then, you can think "correctness" less strictly.
示例:銷售汽車的公司必須測試 ECU.基本上是一個硬件,運行一個潛在的巨大軟件堆棧.這些 ECU 通常在 汽車 內運行.所以當你想對一個ECU進行集成測試時,你必須把ECU放到汽車中進行測試,對吧?一輛可能還不存在的汽車.這里的解決方案:有硬件模擬器.您將 ECU 插入該仿真器,然后 ECU 會思考"位于真車內的內容.
Example: companies selling cars have to test ECUs. Basically a piece of hardware, running a potentially huge software stack. These ECUs normally operate within cars. So when you want to integration test an ECU, you would have to put the ECU into a car for testing, right? A car that probably doesn't exist yet. The solution here: there are hardware emulators. You plug the ECU into that emulator, and the ECU "thinks" that sits inside a real car.
所以:有很好的論據聲稱真正的集成測試不能使用模擬",但與此同時,在現實世界中,這種模擬"一直在發生.
So: there are good arguments to claim "a true integration test can't use mocking", but at the same time, in the real world, such "mocking" happens all the time.
因此,真正的答案是:這取決于上下文.因此,沒有一個普遍的答案.相反,這是關于溝通.您只需"確保您的組/組織中的所有人都對這些術語有相同的理解.
The real answer is therefore: it depends on context. Therefore there isn't a universal answer. Instead, this is about communication. You "simply" have to ensure that all people in your group/org have the same understanding of such terms.
這個詞本身可以用不同的方式來解釋.您(共同!)選擇最適合您需求的定義,然后確保所有為您的項目做出貢獻的人都共享該觀點(或至少了解它).
The term itself can be interpreted in different ways. You (jointly!) pick that definition that best fits your needs, to then make sure all people contributing to your project share that view (or at least know about it).
這篇關于在集成測試中進行模擬是否被認為是一種好習慣?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!