Integrating Salve with Guice and TestNG

1 view
Skip to first unread message

hbf

unread,
Aug 17, 2009, 6:11:35 AM8/17/09
to Salve
Dear list,

I am trying to set up a comfortable testing infrastructure using
TestNG and Guice. I have come up with this base class; actual tests
will inherit from it:

public abstract class AbstractGuiceInjectedTest extends AbstractModule
{
protected final Injector injector;

public AbstractGuiceInjectedTest()
{
injector = Guice.createInjector(this);
injector.injectMembers(this);
}

public Injector getInjector()
{
return injector;
}
}

Here's a sample test to illustrate the usage:

public class FirstGuiceTest extends AbstractGuiceInjectedTest
{
@Inject
@Named("foo")
private String isBar;

@Test
public void test()
{
Assert.assertEquals(isBar, "bar");
}

@Override
protected void configure()
{
bindConstant().annotatedWith(Names.named("foo")).to("bar");
}
}

In order to support Salve, I subclassed AbstractGuiceInjectedTest as
follows:

public abstract class AbstractSalveAndGuiceInjectedTest extends
AbstractGuiceInjectedTest
{
public AbstractSalveAndGuiceInjectedTest()
{
DependencyLibrary.addLocator(new GuiceBeanLocator(injector));
}

@AfterClass(alwaysRun = true)
public void tearDown()
{
DependencyLibrary.clear(); // (*) see below
}
}

Two questions:

1. Do you see a way to improve that further (less boilerplate code,
easier to use, etc.)?

2. The problem with the above code is that running several tests in
the same virtual machine does not (necessarily) work. Without line
(*), the GuiceBeanLocator gets installed and if, say, a Spring-only
(i.e., not using Guice) test runs afterwards, the locator causes
trouble. With the line (*), I am worried that parallel tests will not
work. Is there a better way to deal with this problem?

Thanks,
Kaspar

Igor Vaynberg

unread,
Aug 17, 2009, 3:04:20 PM8/17/09
to salve...@googlegroups.com
if you are planning to run your tests in parallel one way to make this
work is to create a locator decorator that also takes the thread name
and only locates objects for that thread.

library.clear() will still cause a problem however. maybe all locators
for the test can be grouped into a single one and dependencylibrary
can provide the means to remove a specific locator.

-igor
Reply all
Reply to author
Forward
0 new messages