2015-10-16 140 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

不确定这两种方法是否可以一起使用,但绝对值得尝试。