2015-10-16 130 views
4

如何避免guice鍋爐板?如何避免Guice鍋爐板代碼

隨着春天,我通常使用@AutoWired和多數民衆贊成在它,沒有createInjector,沒有injectMemebers(this)。有沒有辦法避免使用giuce的人呢?是否有一些我可以做的全局設置,我會自動將所有東西注入應用程序和測試類中?

public class AccountDaoTest { 
    @Before 
    public void setup() { 
     Injector injector; 
     injector = Guice.createInjector();// I don't want this boiler-plate 
     injector.injectMembers(this); 
    } 

    @Inject 
    AccountDAO accountDao ; 


    @Test 
    public void persist(){ 
     Account ac = new Account(); 
     ac.setName("AccountName"); 
     ac.setAccountType(AccountType.Hospital); 
     accountDao.createAccount(ac); 

    } 
} 
+0

編寫一個基類或JUnit'@ Rule'來爲你做這件事嗎? –

+0

@Tavian,我寧願避免「MyTest擴展BaseTest」。在Test類中尋找類似於_AT_WithGuice的註釋行。 – Espresso

+0

那麼'@ Rule'可以避免擴展一個基類。還有Jukito和@ Jan的建議。 –

回答

2

我猜你正在尋找的東西像SpringJunitRunner的吉斯:https://github.com/caarlos0/guice-junit-test-runner

@RunWith(GuiceTestRunner.class) 
@GuiceModules(MyModule.class) 
public class MyTest { 
    @Inject 
    private Something something; 

    @Test 
    public void testItWorks() throws Exception { 
     Assert.assertThat(something.doSomething(), CoreMatchers.notNullValue()); 
    } 
} 
+0

謝謝。我看了一下這個例子,代碼給出了RunWith。但是我們仍然需要在另一個地方添加「custom」boiler-plate-wiring「代碼:例如:bind(Worker.class).to(MyWorker.class);好奇我們怎樣才能避免」定製「 MyWorker,並創建MyModules,即自動發現和注入的方式。 – Espresso

0

正如揚建議,你可以使用測試運行器手動進樣器建設應對。爲了消除使用帶有測試綁定的單次使用模塊的需要,從Guice 4開始有新的「綁定字段」功能(請參閱wiki page

不確定這兩種方法是否可以一起使用,但絕對值得嘗試。