Spring测试类

编程入门 行业动态 更新时间:2024-10-23 05:42:33

Spring<a href=https://www.elefans.com/category/jswz/34/1771117.html style=测试类"/>

Spring测试类

文章目录

  • JUnit5
    • 引入依赖
    • 添加配置文件
    • 添加java类
    • 测试
  • JUnit4
    • 添加依赖
    • 测试

JUnit5

引入依赖

<dependencies><!--spring context依赖--><!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.2</version></dependency><!--spring对junit的支持相关依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.0.2</version></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.9.0</version></dependency><!--log4j2的依赖--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.19.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j2-impl</artifactId><version>2.19.0</version></dependency>
</dependencies>

添加配置文件

beans.xml
开启注解扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xmlns:context=""xsi:schemaLocation=" .xsd .xsd"><context:component-scan base-package="com.atguigu.spring6.bean"/>
</beans>

添加java类

import org.springframework.stereotype.Component;@Component
public class User {public User() {System.out.println("run user");}
}

测试

//两种方式均可
//方式一
//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:beans.xml")
//方式二
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class SpringJUnit5Test {// 注解引入user类@Autowiredprivate User user;@Testpublic void testUser(){System.out.println(user);}
}

JUnit4

JUnit4在公司也会经常用到,在此也学习一下

添加依赖

<!-- junit测试 -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version>
</dependency>

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class SpringJUnit4Test {@Autowiredprivate User user;@Testpublic void testUser(){System.out.println(user);}
}

更多推荐

Spring测试类

本文发布于:2023-12-07 10:23:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1670984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!