Injection and TestCases

Very easy - but only if you already know both TestNG and google-guice!!!

Step 1: define your business objects

interface Service {

    void go();

}

class ServiceImpl implements Service {

    public void go() {
        System.out.println("This is a test message");
    }

}

Step 2: define now the TestNG Object Factory

class ServiceTestObjectFactory extends com.testnguice.inject.AbstractGuiceObjectFactory {

    public ServiceTestObjectFactory() {
        super(new Module() {
            public void configure(Binder binder) {
                binder.bind(Service.class).to(ServiceImpl.class);
            }
        });
    }

}

Step 3: define your test case(s)

class ServiceTestCase {

    @com.google.inject.Inject
    private Service service;

    public void setService(Service service) {
        this.service = service;
    }

    @org.testng.annotations.Test
    public void verifyExpectedMessage() {
        assert "This is a test message".equals(service.getMessage());
    }

}

Step 4: configure testng.xml in way to specify the Object Factory

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="my-test-suite">

    <test name="my-test">
        <classes>
            <class name="ServiceTestObjectFactory"/>
            <class name="ServiceTestCase"/>
        </classes>
    </test>

</suite>

Don't forget to specify the Object Factory before the rest of test classes!!!

Final step: Run TestNG and enjoy :)