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 分钟前
状态机设计:比if-else优雅100倍的设计
后端
考虑考虑2 小时前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
涡能增压发动积2 小时前
一起来学 Langgraph [第三节]
后端
sky_ph2 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
涡能增压发动积2 小时前
一起来学 Langgraph [第二节]
后端
TTDreamTT2 小时前
SpringBoot十二、SpringBoot系列web篇之过滤器Filte详解
spring boot
hello早上好3 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
roman_日积跬步-终至千里3 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
00后程序员4 小时前
提升移动端网页调试效率:WebDebugX 与常见工具组合实践
后端
HyggeBest4 小时前
Mysql的数据存储结构
后端·架构