ooServiceImpltest:
@SpringBootTest(classes = FooServiceImpl.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子2:使用内嵌@Configuration加载Bean
源代码见FooServiceImpltest:
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
@Configuration
@Import(FooServiceImpl.class)
static class Config {
}
}
例子3:使用外部@Configuration加载Bean
Config:
@Configuration
@Import(FooServiceImpl.class)
public class Config {
}
FooServiceImpltest:
@SpringBootTest(classes = Config.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
这个例子和例子2差不多,只不过将@Configuration放到了外部。
例子4:使用@SpringBootConfiguration
前面的例子@SpringBootTest的用法和@ContextConfiguration差不多。不过根据@SpringBootTest的文档:
- 它会尝试加载@SpringBootTest(classes=…)的定义的Annotated classes。Annotated classes的定义在ContextConfiguration中有说明。
- 如果没有设定@SpringBootTest(classes=…),那么会去找当前测试类的nested @Configuration class
- 如果上一步找到,则会尝试查找@SpringBootConfiguration,查找的路径有:1)看当前测试类是否@SpringBootConfiguration,2)在当前测试类所在的package里找。
所以我们可以利用这个特性来进一步简化测试代码。
Config:
@SpringBootConfiguration
@Import(FooServiceImpl.class)
public class Config {
}
FooServiceImpltest:
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子5:使用@ComponentScan扫描Bean
前面的例子我们都使用@Import来加载Bean,虽然这中方法很精确,但是在大型项目中很麻烦。
在常规的Spring Boot项目中,一般都是依靠自动扫描机制来加载Bean的,所以我们希望我们的测试代码也能够利用自动扫描机制来加载Bean。
Config:
@SpringBootConfiguration
@ComponentScan(basePackages = "me.chanjar.basic.service")
public class Config {
}
FooServiceImpltest:
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子6:使用@SpringBootApplication
也可以在测试代码上使用@SpringBootApplication,它有这么几个好处:
- 自身SpringBootConfiguration
- 提供了@ComponentScan配置,以及默认的excludeFilter,有了这些filter Spring在初始化ApplicationContext的时候会排除掉某些Bean和@Configuration
- 启用了EnableAutoConfiguration,这个特性能够利用Spring Boot来自动化配置所需要的外部资源,比如数据库、JMS什么的,这在集成测试的时候非常有用。
Config:
@SpringBootApplication(scanBasePackages = "me.chanjar.basic.service")
public class Config {
}
FooServiceImpltest:
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGS