考虑一个典型的Netflix Governator junit测试。
public class SampleWithGovernatorJunitSupportTest {
@Rule
public LifecycleTester tester = new LifecycleTester();
@Test
public void testExampleBeanInjection() throws Exception {
tester.start();
Injector injector = tester
.builder()
.withBootstrapModule(new SampleBootstrapModule())
.withModuleClass(SampleModule.class)
.usingBasePackages("sample.gov")
.build()
.createInjector();
BlogService blogService = injector.getInstance(BlogService.class);
assertThat(blogService.get(1l), is(notNullValue()));
assertThat(blogService.getBlogServiceName(), equalTo("Test Blog Service"));
}
}
该测试利用了Netflix Governator提供的Junit规则支持,并测试了Governator的某些功能集-引导模块,程序包扫描,配置支持等。
但是,该测试有很多样板代码,我觉得可以通过使用Junit Runner类型的模型来减少。 作为这个概念的证明,我将介绍一个没有想象力的项目– Governorator-junit-runner ,现在考虑使用该库重写的同一测试:
@RunWith(GovernatorJunit4Runner.class)
@LifecycleInjectorParams(modules = SampleModule.class, bootstrapModule = SampleBootstrapModule.class, scannedPackages = "sample.gov")
public class SampleGovernatorRunnerTest {
@Inject
private BlogService blogService;
@Test
public void testExampleBeanInjection() throws Exception {
assertNotNull(blogService.get(1l));
assertEquals("Test Blog Service", blogService.getBlogServiceName());
}
}
现在,大多数样板都在Junit运行器中实现,并且通过LifecycleInjectorParams批注传递引导监管程序所需的参数。 测试实例本身是一个绑定的组件,因此可以被注入到其中,这样可以将需要测试的实例注入到测试本身中并声明。 如果您想要更细粒度的控制,则可以将LifecycleManager本身注入到测试中!:
@Inject
private Injector injector;
@Inject
private LifecycleManager lifecycleManager;