user1730789
user1730789

Reputation: 5177

Using RoboGuice to inject Classes in my activity

I am new to using roboguice and i am having a hard time configuring injection in my application.

Say that i have the following interface

public interface IAPICall{
         void doSomething();
}

and i have two different implementations of my interface

public class MyApiCall implements IAPICall{
   public void doSomething(){
   }
}



 public class MyMockApicall implements IAPICall{
       public void doSomething(){
       }
    }

Now my requirement is that i want to inject the interface into my activity. How do i configure which concrete class gets injected. During testing i want to inject my mock class while during production i want to inject the actual class. How can i configure this ?

Kind Regards

Upvotes: 1

Views: 1132

Answers (1)

Gomoku7
Gomoku7

Reputation: 1372

In your guice configuration module :

public class GuiceConfigurationModule extends AbstractModule {
...
    @Override
protected void configure() {
        ...
        bind(IAPICall.class).to(MyApiCall.class);
        ...
    }
...
}

In your activity :

@Inject
IAPICall someApiCall;

The best way to play with a mocked interface during test is to create a test module where the binding are pointing to mockup classes. There is a tutorial on Robolectric on how to do that.

http://pivotal.github.com/robolectric/roboguice.html

To add your module to your application, add a roboguice.xml file in the values ressources folder :

 <?xml version="1.0" encoding="utf-8"?>
  <resources> 
    <string-array name="roboguice_modules">
        <item>com.stackoverflow.test.GuiceConfigurationModule</item>
    </string-array>
  </resources>

This is described here :

http://code.google.com/p/roboguice/wiki/UpgradingTo20

Upvotes: 1

Related Questions