2016-12-01 45 views
2

我有一個情況我需要測試的功能,但該類注入字符串值是這樣的:進樣串入類使用吉斯的JUnit測試

public class SomeClass{ 
    @Inject 
    @Named("api") 
    private String api; 

    public Observable<String> get(String uuidData){ 
     //do something with "api" variable 
    } 
} 

現在我該怎樣從我的JUnit測試注入該案件?我也在使用Mockito,但它不允許我模擬原始類型。

回答

4

它看起來像有兩個選項:

選項1:設置注射JUnit測試

//test doubles 
String testDoubleApi; 

//system under test 
SomeClass someClass; 

@Before 
public void setUp() throws Exception { 
    String testDoubleApi = "testDouble"; 
    Injector injector = Guice.createInjector(new Module() { 
     @Override 
     protected void configure(Binder binder) { 
      binder.bind(String.class).annotatedWith(Names.named("api")).toInstance(testDouble); 
     } 
    }); 
    injector.inject(someClass); 
} 

選項2的@Before重構你的類使用的構造注射劑

public class SomeClass{ 
    private String api; 

    @Inject 
    SomeClass(@Named("api") String api) { 
     this.api = api; 
    } 

    public Observable<String> get(String uuidData){ 
     //do something with "api" variable 
    } 
} 

現在您的@Before方法是這樣的:

//test doubles 
String testDoubleApi; 

//system under test 
SomeClass someClass; 

@Before 
public void setUp() throws Exception { 
    String testDoubleApi = "testDouble"; 
    someClass = new SomeClass(testDoubleApi); 
} 

出了兩種選擇的,我要說的第二個最好。你可以看到它導致更少的鍋爐板,並且班級甚至可以在沒有Guice的情況下進行測試。