0

I have my project structure like below:

enter image description here

Where my Test1.java is like this:

package TestNG;

import org.testng.annotations.Test;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class Test1 {

@Inject
@Named("semi-auto.firstname")
String firstname;

@Test
public void test() {
    System.out.println(firstname);
}

}

and my semi-auto.properties is

semi-auto.firstname=John
semi-auto.lastname=Doe

What I want to do is to just use 'firstname' parameter value in Test1 using Guice. The test passes but the value passed is null. Can't I do that this way? Please help

EdXX
  • 872
  • 1
  • 14
  • 32

1 Answers1

2

You need to write a module to configure guice to load the properties file (and bind in any other dependencies you have).

class SemiAutoModule extends AbstractModule {
        @Override
        protected void configure() {
            Properties defaults = new Properties();
            defaults.setProperty("semi-auto.firstname", "default firstname");
            try {
                Properties properties = new Properties(defaults);
                properties.load(ClassLoader.class.getResourceAsStream("semi-auto.properties"));
                Names.bindProperties(binder(), properties);
            } catch (IOException e) {
                logger.error("Could not load config: ", e);
                System.exit(1);
            }
        }
    };

Then you need to tell TestNG about it:

@Guice(modules=SemiAutoModule.class)
public class Test1 {

    @Inject
    @Named("semi-auto.firstname")
    String firstname;

    @Test
    public void test() {
        System.out.println(firstname);
    }

}

The documentation for TestNG is here: http://testng.org/doc/documentation-main.html#guice-dependency-injection.

Panu Haaramo
  • 2,932
  • 19
  • 41
Richard Vodden
  • 318
  • 3
  • 12