【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,运行结果:

相关推荐
pjx9871 小时前
质量的“试金石”:精通Spring Boot单元测试与集成测试
spring boot·spring·单元测试·集成测试
2401_837088501 小时前
eclipse怎么导入junit4
java·junit·eclipse
幼儿园口算大王1 小时前
Spring反射机制
java·spring·反射
Howard_Stark3 小时前
Spring生命周期
spring
计算机毕设定制辅导-无忧学长3 小时前
Spring 与 ActiveMQ 的深度集成实践(二)
spring·activemq·java-activemq
溪i4 小时前
react-spring/web + children not defined
前端·spring·react.js
带刺的坐椅5 小时前
qwen3 惊喜发布,用 ollama + solon ai (java) 尝个鲜
java·spring·solon·solon-ai·qwen3
命中的缘分5 小时前
SpringCloud原理和机制
后端·spring·spring cloud
Howard_Stark5 小时前
Spring的BeanFactory和FactoryBean的区别
java·后端·spring
再拼一次吧6 小时前
Spring进阶篇
java·后端·spring