【Spring整合Junit】Spring整合Junit介绍

本文内容基于【Spring整合MyBatis】Spring整合MyBatis的具体方法进行测试

文章目录

  • [1. 导入相关坐标](#1. 导入相关坐标)
  • [2. 使用Junit测试所需注解](#2. 使用Junit测试所需注解)
  • [3. 在测试类中写相关内容](#3. 在测试类中写相关内容)

1. 导入相关坐标

在pom.xml中导入相关坐标:

xml 复制代码
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.25</version>
</dependency>

2. 使用Junit测试所需注解

一般测试Service类,我们在test包下建立测试类,并使用@Runwith来指定运行期,通过@ContextConfiguration来指定配置类

java 复制代码
package com.example.project2.service;

import com.example.project2.config.SpringConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
}

关于@Runwith找了两篇博客:

  1. Junit的基础讲解一
  2. Junit的基础讲解二

3. 在测试类中写相关内容

使用依赖注入在这里注入accountService,在测试方法中上需要加上@Test的注解

java 复制代码
package com.example.project2.service;

import com.example.project2.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFIndById(){
        System.out.println(accountService.findById(1));
    }
}

运行结果:

findById()中的id改成2,运行结果:

相关推荐
JavaGuide3 小时前
推荐一个基于 Spring Boot 4.0 + Java 21 + Spring AI 2.0 的大模型项目!
java·spring boot·spring
NE_STOP4 小时前
spring6-多种类型的注入方式
spring
小马爱打代码4 小时前
Spring Boot :使用 Spring Cache 注解方式集成 Redis
spring boot·redis·spring
有味道的男人4 小时前
1688获得商品类目调取商品榜单
java·前端·spring
树码小子5 小时前
SpringMCV(9)响应:返回静态页面 & 修改响应数据
spring·mvc
Remember_9935 小时前
Spring 事务深度解析:实现方式、隔离级别与传播机制全攻略
java·开发语言·数据库·后端·spring·leetcode·oracle
roman_日积跬步-终至千里6 小时前
【Java并发】用 JMM 与 Happens-Before 解决多线程可见性与有序性问题
java·开发语言·spring
独断万古他化6 小时前
【Spring 核心:AOP】基础到深入:思想、实现方式、切点表达式与自定义注解全梳理
java·spring·spring aop·aop·切面编程
树码小子7 小时前
SpringMVC(10)综合案例练习:计算器,登录
spring·mvc
roman_日积跬步-终至千里7 小时前
【Java并发】Tomcat 与 Spring:后端项目中的线程与资源管理
java·spring·tomcat