[英]Is it possible to override a call to an injector?
我是Spock和Guice的新手。 我正在嘗試測試我的課程,但是我不知道如何通過交互覆蓋下面的調用。
測試:
@Shared def INSVariableResolver resolver // just a wrapper of my injector, it's an interface
@Shared def MyInterface myMock = Mock()
def setupSpec(){
given:
injector = Guice.createInjector(modules)
resolver = injector.getInstance(INSVariableResolver)
resolver.getInstance(MyInterface.class) >> myMock // INTERACTION
}
def "some test"(){
given:
AnotherInterface someObject = resolver.getInstance(AnotherInterface)
expect:
someObject.doSomething() == someValue
}
另一個接口的實現:
class AnotherClass implements AnotherInterface{
@Inject
INSVariableResolver resolver;
public int doSomething(){
.
.
MyInterface i = resolver.getInstance(MyInterface.class); // (*) trying to override this call
.
.
}
但這是行不通的。 我是標有(*)的行上的真實對象,不是模擬對象。 我既不想更改實現,也不想更改AbstractModule。
有可能做我想做的事嗎? 我是否以錯誤的方式使用交互? 謝謝
更新:我只需要在AnotherClass中模擬MyInterface。
您不應該使用Spock模擬Guice,但是可以通過覆蓋模塊來配置Guice注入模擬而不是真實實例。
def setupSpec(){
injector = Guice.createInjector(Modules.override(modules).with(new Module() {
public void configure(Binder binder) {
binder.bind(MyInterface).toInstance(myMock)
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.