junit 的使用以及springboot整合junit的使用 单元测试不能运行单个方法的原因

1 篇文章 0 订阅
1 篇文章 0 订阅

1.首先导入依赖,junit的普通使用以及springboot的整合都可以使用这一套依赖


		<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>

2.普通使用

	@Test
	public void CommonUse() {
		System.out.println("this is a common  method");
	}

它的特点是不能使用spring的相关功能,比如注解,框架等,但是对于普通的代码块是可以使用的,有时候我们junit5不能运行,需要调整到junit4,在run as → run config调整至junit4 ,
在这里插入图片描述
3.springboot 整合junit使用,示例代码如下:

package com.example.demo.createtest;

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;

/*Springboot测试类
 * @Runwith:启动器
 * SpringJUnit4ClassRunner.class   让junit与spring环境进行整合
 * 
 * @SpringBootTest
 * 1.声明当前类为springboot的测试类
 * 2.加载springboot的启动类,启动spring boot
 * */
import com.example.demo.RabbitMqDemoApplication;
import com.example.demo.dao.UserMapper;
import com.example.demo.model.User;

@RunWith(SpringRunner.class)//idea似乎不需要这个注解
@SpringBootTest(classes = {RabbitMqDemoApplication.class})
public class SpringbootTest {
	
	@Autowired
	private UserMapper  userMapper;
	
	@Test
	public void test_1() throws InterruptedException {
		System.out.println("come in");
		User sel = userMapper.Sel(1);
		System.out.println("xxxxxxxxxx"+sel.toString());
		
		Thread.sleep(20000);
	}
}

需要注意的是需要在类前面添加注解@Runwith和@SpringBootTest,@SpringBootTest里面的为该项目的启动类,这样的话就可以运行注解等和spring相关的功能,运行方法同普通使用的方法
3.一些使用问题
光标要落在方法名上面,右击运行,而不是在别的地方,如:
在这里插入图片描述

  • 程序包org.junit不存在
    这是引用出了问题,而已把导入junit包的语句放在最前面,就会发现一些包出现了错误,然后ctrl+shift+o吧所有包重新导一下,也可以把所有的导包语句删掉,快捷键重新导包。

  • @MockBean注解使用 (其实就相当于一个挡板,对于未实现,或者很难调用的,做一个虚拟返回值)
    在这里插入图片描述
    在实际开发中,我们自己写的Controller、Service很可能去调用别的同事或别的项目组写的Service、Mapper,对方可能只写了一个接口,没有实现(比如本例中我写的Mapper),这样是没法进行测试的。

Mock的作用:创建一个虚拟的对象替代那些不易构造或不易获取的对象。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PH = 7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值