How can I create a Guice injector for every scenario?

517 views
Skip to first unread message

ralp...@gmail.com

unread,
Dec 19, 2016, 4:57:11 AM12/19/16
to Cukes
Hi all,

for the test of our system I am using a lot of framework code that has been generated.
This also contains many generated Guice modules.
Within those modules there are e.g. data managers that are already scoped as @Singleton.

Right now we are using Fitnesse for integration tests, but would like to change to Cucumber.
In Fitnesse, we created the injector ourselves and would simply create a new injector every time we start a single test. That way all data managers are always fresh and new.
In Cucumber the injector is created once from an InjectorSource.
How can I make sure this InjectorSource creates a new injector for every scenario?

Thanks,
Ralph

Jurn van Mieghem

unread,
Dec 21, 2016, 9:44:05 AM12/21/16
to Cukes
I am not that familiar in Guice, but in Cucumber-guice there is something like @ScenarioScoped



Op maandag 19 december 2016 10:57:11 UTC+1 schreef ralp...@gmail.com:

ralp...@gmail.com

unread,
Dec 22, 2016, 3:02:25 AM12/22/16
to Cukes
This is correct and I could use this annotation to create a module that overrides all @Singleton scopes with @ScenarioScoped.
But this solution would be very tideous, because we are talking about A LOT of scope definitions.
Like I said, the original modules are created by a code generator from a data model. The model possibly contains many hundreds of type definitions.

Therefore it would be easier to recreate the complete injector instead for each scenario. This would reset all singleton-scoped instances.
Problem is that I don't find a way to recreate the injector with every scenario. The InjectorSource is called only  once when Cucumber starts.

Are there any other possibilities?

Ralph

ralp...@gmail.com

unread,
Jan 2, 2017, 9:03:00 AM1/2/17
to Cukes
Ok, after a lot of research I have found the answer myself in an old article of Aslak.
It seems that coming up with a custom ObjectFactory is the correct answer. The instantiation of the ObjectFactory is done in cucumber.properties:

cucumber.api.java.ObjectFactory=my.package.CustomObjectFactory

In the start() method of the ObjectFactory I can now recreate a new injector for each scenario.
It works.

Ralph

Trond

unread,
Apr 28, 2017, 8:20:29 AM4/28/17
to Cukes
Wouldn't it be best if the default behavior of the GuiceFactory actually created a new injector in the start() method, as this is probably what one would want for each scenario any way? To have a clean setup at the start of the scenario. F.ex if used with a mocking framework, 
and mocks have been injected into the step-definition and one is counting invocations, it is better to have a new injector created than to reset all mocks on some @after annotated method, right?

Trond
Reply all
Reply to author
Forward
0 new messages