Spring Boot整合Junit

一、main方法启动spring

new ClasspathXmlApplicationContext("applicationContext.xml");

二、spring整合junit

//@RunWith(SpringJUnit4ClassRunner.class)

@RunWith(SpringRunner.class)

@ContextConfiguration("classpath:applicationContext.xml")

三、springboot整合junit

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes={SpringbootJunit.class})

Junit启动器

XML 复制代码
<!--junit启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency

编写业务代码

dao

java 复制代码
@Repository
public class UserDaoImpl {

	public void saveUser(){
		System.out.println("insert into users.....");
	}
}

service

java 复制代码
@Service
public class UserServiceImpl {

	@Autowired
	private UserDaoImpl userDaoImpl;
	
	public void addUser(){
		this.userDaoImpl.saveUser();
	}
}

app

java 复制代码
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

整合Junit

java 复制代码
/**
 *  main方法:
 *		ApplicationContext ac=new 
 *       			ClassPathXmlApplicationContext("classpath:applicationContext.xml");
 *  junit与spring整合:
 *      @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合
 *   	@Contextconfiguartion("classpath:applicationContext.xml")  
 */
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes={App.class})
public class UserServiceTest {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Test
	public void testAddUser(){
		this.userServiceImpl.addUser();
	}
}
相关推荐
喵个咪20 分钟前
Go 接口与代码复用:替代继承的设计哲学
后端·go
喵个咪21 分钟前
ASIO 定时器完全指南:类型解析、API 用法与实战示例
c++·后端
IT_陈寒1 小时前
Vite 3.0 重磅升级:5个你必须掌握的优化技巧和实战应用
前端·人工智能·后端
gadiaola1 小时前
【计算机网络面试篇】HTTP
java·后端·网络协议·计算机网络·http·面试
bcbnb1 小时前
HTTP抓包工具Fiddler使用教程,代理设置、HTTPS配置与接口调试实战指南
后端
昕昕恋恋1 小时前
Kotlin 中类成员访问权限的实践与辨析
后端
BD_Marathon2 小时前
sbt 编译打包 scala
开发语言·后端·scala
有风632 小时前
优先级队列详解
后端
雨中飘荡的记忆2 小时前
ByteBuddy 实战指南
后端
Apifox2 小时前
Apifox 11 月更新|AI 生成测试用例能力持续升级、JSON Body 自动补全、支持为响应组件添加描述和 Header
前端·后端·测试