首先我们来回顾一下 Spring
整合 junit
@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
注入要测试的资源创建一个新的SpringBoot工程
在com.blog.service包下创建BookService接口
public interface BookService {
void save();
}
在com.blog.service.impl包下创建BookService接口的实现类,并重写其方法
@Service
public class BookServiceImpl implements BookService {
@Override
public void save() {
System.out.println("book service is running ..");
}
}
在 test/java
下创建 com.blog
包,在该包下创建测试类,将 BookService
注入到该测试类中
@SpringBootTest
class Springboot02JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
void contextLoads() {
bookService.save();
}
}
<aside> 🌷 注意:这里的引导类所在包必须是测试类所在包及其子包。
例如:
com.blog
com.blog
如果不满足这个要求的话,就需要在使用 @SpringBootTest
注解时,使用 classes
属性指定引导类的字节码对象。如 @SpringBootTest(classes = XxxApplication.class)
</aside>