問(wèn)題描述
是否可以使用 EasyMock 創(chuàng)建一個(gè)實(shí)現(xiàn)多個(gè)接口的模擬對(duì)象?
Is it possible to create a mock object that implements several interfaces with EasyMock?
例如接口Foo
和接口Closeable
?
在 Rhino Mocks 中,你可以在創(chuàng)建 mock 對(duì)象時(shí)提供多個(gè)接口,但 EasyMock 的 createMock()
方法只接受一種類(lèi)型.
In Rhino Mocks you can provide multiple interfaces when creating a mock object, but EasyMock's createMock()
method only takes one type.
是否可以使用 EasyMock 來(lái)實(shí)現(xiàn)這一點(diǎn),而無(wú)需求助于創(chuàng)建一個(gè)擴(kuò)展 Foo
和 Closeable
的臨時(shí)接口,然后對(duì)其進(jìn)行模擬?
Is it possbile to achieve this with EasyMock, without resorting to the fallback of creating a temporary interface that extends both Foo
and Closeable
, and then mocking that?
推薦答案
EasyMock 不支持此功能,因此您只能使用臨時(shí)界面的回退.
EasyMock doesn't support this so you're stuck with fallback of the temporary interface.
順便說(shuō)一句,我聞到了一點(diǎn)代碼的味道——如果一個(gè)方法真的將一個(gè)對(duì)象視為 2 個(gè)不同的東西,Foo
和 Closeable
接口這個(gè)案例?
As an aside, I smell a little bit of a code wiff - should a method really be treating an object as 2 different things, the Foo
and Closeable
interface in this case?
這對(duì)我來(lái)說(shuō)意味著該方法正在執(zhí)行多個(gè)操作,雖然我懷疑其中一個(gè)操作是關(guān)閉"Closeable
,但調(diào)用代碼決定是否更有意義是否需要關(guān)閉"?
This implies to me that the method is performing multiple operations and while I suspect one of those operations is to 'close' the Closeable
, wouldn't it make more sense for the calling code to decide whether or not the 'close' is required?
以這種方式構(gòu)建代碼將打開(kāi)"和關(guān)閉"保持在同一個(gè) try ... finally
塊中,恕我直言,讓代碼更具可讀性,更不用說(shuō)該方法更通用,并允許您傳遞僅實(shí)現(xiàn) Foo
的對(duì)象.
Structuring the code this way keeps the 'open' and 'close' in the same try ... finally
block and IMHO makes the code more readable not to mention the method more general and allows you to pass objects that only implement Foo
.
這篇關(guān)于是否可以使用 EasyMock 創(chuàng)建一個(gè)實(shí)現(xiàn)多個(gè)接口的模擬對(duì)象?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!