chaitra.kear
chaitra.kear

Reputation: 67

How to unit test a class which has field injection (using guice)

Class under test looks like this :

public class SomeAdapter {

@Inject
HttpService httpService;

@Inject
Configuration configuration;

public SomeAdapter()
{
    GuiceInjector.getInjector().injectMembers(this);
}

public String getBaseUrl()
{
    return configuration.getProtocol()+ "://" + some.getServer() + ":" + configuration.getPort();
  }
}

I have tried InjectMocks from the mockito framework, but it does not seem reliable.Would creating a seperate test module which extends AbstractModule be necessary?

Upvotes: 2

Views: 3645

Answers (1)

volkovs
volkovs

Reputation: 1183

I would suggest injecting dependencies outside the class (that would follow single responsibility principle). Then you might use standard Mockito:

@RunWith(MockitoJUnitRunner.class)
public class SomeAdaptorTest {

  @Inject
  Configuration configuration;

  @InjectMocks
  SomeAdaptor adaptor = new SomeAdaptor();

  @Before
  public void setUp() {
    when(configuration.getId()).thenReturn(5);
  }
  ...

Or creating another constructor, package private, to accept mocked dependencies.

Upvotes: 5

Related Questions