0
点赞
收藏
分享

微信扫一扫

springboot整合Junit框架、Redis框架

Raow1 2022-04-13 阅读 54

springboot整合Junit框架

实现步骤:

  1. 搭建Springboot工程,命名为springboot-test。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    完成。

  2. 引入starter-test起步依赖,快速构建springboot项目自带这个依赖,可以到pom.xml文件中查看,不需要操作

  3. 编写测试类,如果是MAVEN项目就写到test包下
    首先在main/java/com.example.springboottest包下编写一个业务类,方便以后进行测试。先简单写个add()方法

package com.example.springboottest;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void add(){
        System.out.println("add...");
    }
}

然后去test/java/com.example.springboottest包下删除原来自动生成的com.example.springboottest.SpringbootTestApplicationTests,新建一个测试用例类UserServiceTest(命名测试哪个类就是类名+Test)

  1. 给测试类添加测试相关注解
    SpringBoot2.2或者说Junit5 开始没有@RunWith注解,只需加@SpringBootTest 这一个注解就够了,而且不需要写classpath
  2. 编写测试方法
package com.example.springboottest;

/*
UserService的测试类
 */

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testAdd(){//测试方法
        userService.add();
    }
}
  1. 点击testAdd()方法左侧绿色箭头按钮,运行测试方法,可以在控制台看到输出,测试成功。
    在这里插入图片描述

springboot整合Redis框架

  1. 首先要在本机Windows下载安装Redis,下载地址:https://github.com/MSOpenTech/redis/releases。
    Redis 支持 32 位和 64 位,根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包并解压到一个文件夹下(我选的是D盘某个文件夹),在当前文件夹打开 cmd 窗口,运行 redis-server.exe redis.windows.conf,输入之后,会显示如下界面:
    在这里插入图片描述
    Redis启动成功。

  2. 新建模块springboot-redis,模块比工程要小一点,方便进行实验。一样的方法。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    创建完成。

  3. 注入Redis Template,测试Redis,项目在启动时会自动帮我们进行一些配置操作。在SpringbootRedisApplicationTests类中键入如下代码:

package com.example.springbootredis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSet() {
        //存入数据
        redisTemplate.boundValueOps("name").set("zhangsan");//注意boundValueOps()参数先输入"",直接会产生key:"",天坑!
    }

    @Test
    public void testGet(){
        //获取数据
        Object name=redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

}

先运行testSet()方法,存入数据zhangsan,再运行testGet()方法,获取数据,可以在控制台看到结果输出,测试成功。
在这里插入图片描述
但是现在是在本机上的Redis,以后做项目肯定不是用本机的Redis,需要进行redis的配置。在main/resources包下配置即可。新建一个application.yml文件进行配置,可以修改host主机IP,端口号等一系列信息,下面简单举个例子。

spring:
  redis:
    host: 127.0.0.1 #redis的主机IP
    port: 6379 #默认端口号6379
举报

相关推荐

0 条评论