1、引入依赖
<!-- 测试工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
2、创建单元测试
import com.yami.shop.leaf.service.SegmentService;
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;
@SpringBootTest
@RunWith(SpringRunner.class)
public class PushShopApplicationTest {
@Autowired
private SegmentService segmentService;
@Test
public void main() {
segmentService.getSegmentId("test");
System.out.println("hello world");
}
}
目录结构
外层父pom 多个模块,多个端口启动项目多个服务
3、注意事项
1、@Test 注解为org.junit.Test包内的
2、多模块项目,测试类要创建在与web一个模块内 (就是有主程序入口XXXApplication的模块,而不是bean,common 这些没有启动类,没有配置端口的模块,那样会找不到启动入口也扫描不到 @Autowired 的类 bean 依赖会注入不了)
test 包下面的层级关系需要与 main 下面的层级关系一样
3、测试方法不能有返回值,不能为static
4、引入依赖进来不要单独写版本号容易冲突运行不起来
5、@RunWith(SpringRunner.class) 可以当固定写法
6、
@Test
public void main() {
segmentService.getSegmentId("test");
System.out.println("hello world");
}
方法必须是public的