Spring 整合 Junit


一. 导入相关依赖

(1) junit依赖

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

注:Spring 5.x 版本整合Junit时,Junit的版本要求必须在4.12及以上,否则会报错

Spring整合Junit版本问题

(2)spring-test

    <!--Spring-test-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

二. 添加注解

在测试类添加注解:

/**
	* RunWith注解:
	* 作用: 把原有的main方法替换成spring提供的main方法
	* 写法固定
	*/
@RunWith(SpringJUnit4ClassRunner.class)
/**
   * ContextConfiguration注解:
   * locations属性: 用于指定Spring配置文件的路径
   * classes属性: 用于指定注解类所在地的路径
   */
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
// 注解类写法:
//@ContextConfiguration(classes = SpringConfiguration.class)
public class MapperTest {
	//实现自动依赖注入
    @Autowired
    private DepartmentMapper departmentMapper;

    @Test
    public void testCRUD(){
        //使用依赖注入的对象
        System.out.println(departmentMapper);
    }
}

三.示例代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Test
    public void testCRUD(){
        System.out.println(departmentMapper);
    }
}
posted @   DavidH  阅读(185)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示