can a class variable inject new instances of the variable into the classes methods with guice?

79 views
Skip to first unread message

akbac...@gmail.com

unread,
Feb 11, 2016, 3:45:07 PM2/11/16
to google-guice
So I am implementing tests in TestNG and would like to be able to have each test method receive a new copy of the class variables in order to allow for parallelization. Is this possible with Guice? I have had no luck googling for answers, the only info I have seen deals with singletons. Using JUnit is not really a option and I am weary of using Guiceberry as it's not been updated in ages.

Karsten Schulz

unread,
Feb 12, 2016, 8:02:04 AM2/12/16
to google-guice
Hello,

this request is not a Guice problem. This is a general problem in java. As i understand your question, you would like reset a class variable on each test method, but what do you mean with "class variable" in object oriented programming class variable are defined attributes, that are the same value on every object. in java you declarate this with static.
So if you mean static variables, than your goal is to reset this variable value. But the problem is, the initialize of this variable classification is on the first access of this class. That means if the class loader is accessing the first time this class.
To reset this value you have some possiblilities. In general you have to use reflection api. So you should set the value of this field manually on each test method. in JUnit maybe in the setUp() method (@Before)

for example i make this to test the i18n support of my project:
final Class<Messages> messageClazz = Messages.class;
final Field resourceField = messageClazz.getDeclaredField("RESOURCE_BUNDLE");
final Field bundleField = messageClazz.getDeclaredField("BUNDLE_NAME");
resourceField
.setAccessible(true);
bundleField
.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField
.setAccessible(true);
modifiersField
.setInt(resourceField, resourceField.getModifiers() & ~Modifier.FINAL);
Locale.setDefault(_currentLocale);
final ResourceBundle currentBundle = ResourceBundle.getBundle((String) bundleField.get(null));
resourceField
.set(null, currentBundle);

In guice you could reinitialize the injector instance on each test, so the class variable will be reinitialize on every new injector. because guice create an own class loader and create instance in this classloader. On new injector object, another instances are available.

i hope i could you answering your question.
Reply all
Reply to author
Forward
0 new messages