Spring Boot版本:2.7.15
SpringBootTest
注解可以配置以下属性来加速单元测试的执行:
webEnvironment = SpringBootTest.WebEnvironment.NONE
不启动web容器classes = {...}
手动指定需要注册到容器中的类,如果不设置该属性,默认会注册应用中所有类示例代码:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public String queryUsers() {
return userMapper.queryUsersFromDB();
}
}
@Repository
public class UserMapper {
public String queryUsersFromDB() {
return "user list";
}
}
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.NONE,
classes = {UserService.class, UserMapper.class}
)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testUserService() {
assertEquals("user list", userService.queryUsers());
}
}
可以用以下代码输出容器中注册的所有bean:
@Test
public void testUserService() {
assertEquals("user list", userService.queryUsers());
// 查看容器中的bean
System.out.println(ctx.getBeanDefinitionCount());
for (String name : ctx.getBeanDefinitionNames()) {
System.out.println(name);
}
}
结果如下:
容器中只有10个bean
如果不设置@SpringBootTest
的两个属性,结果如下:
容器中有133个bean,执行时间大大增加