@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave(){
bookService.save();
}
}
使用 @RunWith
注解指定运行器,使用 @ContextConfiguration
注解来指定配置类或者配置文件。而 SpringBoot
整合 junit
特别简单,分为以下三步完成
SpringBootTest
注解@Autowired
注入要测试的资源@SpringBootTest
class Springboot02DemoApplicationTests {
@Test
void contextLoads() {
}
// 自动装配
@Autowired
private BookService bookService;
@Test
public void testSave() {
bookService.save();
}
}
注意:这里的引导类所在包必须是测试类所在包及其子包。
例如:
com.north
com.north
如果不满足这个要求的话,就需要在使用 @SpringBootTest
注解时,使用 classes
属性指定引导类的字节码对象。如 @SpringBootTest(classes = Springboot07TestApplication.class)