SpringBoot整合Junit的test单元测试

SpringBoot整合Junit步骤:

1、快速搭建SpringBoot工程

SpringBoot工程创建成功后,删除一些无用的文件后的目录结构如下:

2、以上的SpringBoot工程创建完成之后,在工程的pom文件中会自动导入Junit 的starter-test的起步依赖

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<!--test的起步依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<!--<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>-->
		</dependency>
	</dependencies>

3、编写测试类

package com.example;

import org.springframework.stereotype.Service;

@Service
public class ServiceImpl {

    public void add(){
        System.out.println("ServiceImpl ...");
    }
}

4、添加测试相关的注解

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class

5、编写测试方法,对业务层的类进行测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class
class SpringbootTestApplicationTests {

	@Autowired
	private ServiceImpl serviceImpl; //通过注解注入被测试的类

	@Test  //测试方法注解
	public void testAdd() {
		serviceImpl.add();   //被测试的方法
	}

}

6、执行测试方法

测试效果如下,业务层中被测试类的方法中的输出执行成功

 

总结注意:

a、如果test.java下的测试类所在的包与被测试类的包名一致的话,@SpringBootTest括号中的内容可以不写

@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class

可以写成

@SpringBootTest

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值