简体   繁体   中英

How to Inject a class in JUnit Test with Dagger2

I've been following CoffeeMaker tutorial here . Right now I don't want to override any modules/components in my test but want to inject a Class ElectricHeater into my JUnit Test.

When I do so I get a NullPointerExeception when I invoke heater.on(); Not sure what I'm missing.

Here is the test code.

package coffee;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import javax.inject.Inject;

@RunWith(JUnit4.class)
public final class CoffeeMakerTest {

  @Inject
  Heater heater;

  @BeforeClass
  public static void setUp() {
    CoffeeComponent coffeeComponent = DaggerCoffeeComponent.builder().
    build();

  }

  @Test
  public void testCoffeeMaker() throws Exception {
    heater.on();
  }
}

Modified code

@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface CoffeeComponent {
  CoffeeMaker maker();

  void inject(CoffeeMakerTest coffeeMaker);
}

@Before
public void setUp() {
  CoffeeComponent coffeeComponent = DaggerCoffeeComponent.builder().build();
  coffeeComponent.inject(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM