Jay
Jay

Reputation: 2454

how to inject datasource into testng method execution listener

I have a Method level listener in that looks like this

   public class DefaultListener implements IInvokedMethodListener2 {
       @Autowired
       JdbcTemplate jdbcTemplate;        

        public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        }

        public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        }

        public void beforeInvocation(IInvokedMethod method, ITestResult testResult,
                ITestContext context) {
           updateDatabaseWithTestStartTime();           
        }
        private void updateDatabaseWithTestStartTime() {
           jdbcTemplate.update("....");
        }

        // other methods.
}

How do I autowire jdbcTemplate in the above example? I looked at spring-test and integration with test-ng, but examples like these, are talking about controlling autowiring at test level - My needs are listener specific.

Upvotes: 3

Views: 904

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31257

IInvokedMethodListener2 is a TestNG listener and as such has nothing to do with the Spring TestContext Framework.

If you want to interact with beans in your Spring ApplicationContext in a reusable listener, you will therefore need to implement a Spring TestExecutionListener.

Take a look at the SqlScriptsTestExecutionListener for inspiration on how to implement such a listener.

For further details, read all discussions regarding "TestExecutionListener" in the Testing chapter of the Spring reference manual, paying special attention to the TestExecutionListener configuration section.

Upvotes: 3

Related Questions