SpringBoot工程使用@SpringBootTest快速进入单元测试
1、添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2、编写测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.jason9211.service.IUserService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMain {
@Autowired
IUserService iUserService;
@Test
public void doTest() {
String userName = iUserService.getUserNameById(19890228);
System.out.println("userName : " + userName);
}
}
有个前提,IUserService
接口的实现类必须是Spring环境下的组件,这里才能通过@Autowired
实现注入。
例如:
@Service
public class UserServiceImpl implements IUserService {
....
}
3、执行测试
使用JUnit
执行doTest
方法,进行测试。
测试结果:
userName : Angelababy