Java单元测试学习(一)

news2024/10/6 14:34:28

Java单元测试学习(一)

使用TestContainer和docker结合启动redis

前提

  • docker环境

目录结构

在这里插入图片描述

依赖—这里有个小插曲

配置RedisTemplate时一直报错Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed;---->最后的解决方式是①删除了common-pool2版本号②将jdk的版本从1.8升到了11----->把springboot版本降为2.5.5就不会出现报错

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.atguigu</groupId>
    <artifactId>redis_springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis_springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- test -->
        <testcontainers.version>1.15.3</testcontainers.version>

        <!-- redis -->
        <commons.version>2.9.0</commons.version>

        <!-- lombok -->
        <lombok.version>1.18.12</lombok.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- testcontainer -->
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers</artifactId>
            <version>${testcontainers.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${testcontainers.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- spring2.X集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
<!--            <version>${commons.version}</version>-->
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

相关代码

  • RedisConfig
package com.atguigu.redis_springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

@Configuration
public class RedisConfig {

    @Resource
    private RedisConnectionFactory connectionFactory;

    @Bean
    public RedisTemplate<String,Object> redisTemplate() {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

}


  • RedisTestController
package com.atguigu.redis_springboot.controller;

import com.atguigu.redis_springboot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author snape
 * @create 2022-05-28 21:03
 */
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    @Resource
    private RedisService redisService;

    @GetMapping
    public String testRedis() {
        //设置值到redis
        redisService.set("name","tom");
        //从redis获取值
        String name = redisService.get("name");
        return name;
    }

}

  • RedisService
package com.atguigu.redis_springboot.service;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Snape
 * @create 2023-06-05 11:52
 * @desc
 */
@Component
@RequiredArgsConstructor
public class RedisService {

	private final RedisTemplate<String, String> redisTemplate;

	public void set(String key, String value) {
		redisTemplate.opsForValue().set(key, value);
	}

	public String get(String key) {
		return redisTemplate.opsForValue().get(key);
	}
}

  • RedisSpringbootApplication
package com.atguigu.redis_springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisSpringbootApplication.class, args);
    }

}

  • application.yml
spring:
  application:
    name: redis-springboot

redis:
  database: 0
  timeout: 1800000
  lettuce:
    pool:
      max-active: 20
      max-wait: -1
      max-idle: 5
      min-idle: 0


  • RedisContainer
package com.atguigu.redis_springboot.redis;

import org.testcontainers.containers.GenericContainer;

/**
 * @author Snape
 * @create 2023-06-05 11:41
 * @desc
 */
public class RedisContainer extends GenericContainer<RedisContainer> {

	public static final String IMAGE_VERSION = "redis:latest";
	private static final int DEFAULT_PORT = 6379;

	public RedisContainer() {
		this(IMAGE_VERSION);
	}

	public RedisContainer(String imageVersion) {
		super(imageVersion == null ? IMAGE_VERSION : imageVersion);
		addExposedPort(DEFAULT_PORT);
		start();
	}

	public String getPort() {
		return getMappedPort(DEFAULT_PORT).toString();
	}

}

  • RedisServiceTest
package com.atguigu.redis_springboot.service;

import com.atguigu.redis_springboot.RedisSpringbootApplicationTests;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * @author Snape
 * @create 2023-06-05 13:57
 * @desc
 */
public class RedisServiceTest extends RedisSpringbootApplicationTests {

	@Autowired
	private RedisService redisService;

	@Test
	public void testRedis() {
		redisService.set("name", "tom");
		String name = redisService.get("name");
		assertEquals("tom", name);
	}

	@After
	public void destroy() {
		redisContainer.stop();
	}

}

  • RedisSpringbootApplicationTests
package com.atguigu.redis_springboot;

import com.atguigu.redis_springboot.redis.RedisContainer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest(
        classes = RedisSpringbootApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ExtendWith(SpringExtension.class)
@Testcontainers
public abstract class RedisSpringbootApplicationTests {

	@Container
	public static final RedisContainer redisContainer =
			new RedisContainer();

	@DynamicPropertySource
	public static void registerProperties(DynamicPropertyRegistry registry) {
		registry.add("spring.redis.host", redisContainer::getHost);
		registry.add("spring.redis.port", redisContainer::getPort);
	}

}

测试

  • 在test方法里打上断点,开启debug后可查看到启动的容器
    在这里插入图片描述

  • 测试通过
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/612690.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

客户回访|国产MCU测试解决方案 助力中国“芯”智造

半导体技术持续更新迭代&#xff0c;MCU也在与时俱进&#xff0c;为了更好地迎接市场未来趋势&#xff0c;国产MCU厂商积极布局各系列MCU产品线&#xff0c;开始逐渐在特定细分领域实现突破。随着应用场景的进化升级&#xff0c;MCU 中包含越来越多的功能模块&#xff0c;相应地…

Mysql进阶【1】论述索引,索引数据结构,MVCC

1. ReadView 案例&#xff0c;解释为什么 RR 和 RC 隔离级别下看到查询结果不一致 案例 01- 读已提交 RC 隔离级别下的可见性分析 开启两个回话&#xff0c;会话事务级别都是READ-COMMITED; 操作步骤 开启两个数据库会话&#xff0c;设置事务为提交读事务2查询id1数据&#…

zerotier使用

目标 使用zerotier进行内网穿透&#xff0c;使外网客户端访问内网服务器 步骤 1.1 注册 进入zerotier官网&#xff0c;注册 ​ 完成后进入个人中心&#xff0c;点击networks&#xff0c;选择创建网络&#xff0c;得到一个networkid ​ 点击id进入设置&#xff0c;编辑名称…

程序员——毕业年薪28w真的不可能吗?

我是一名来自湖南的普通应届毕业生。目前就职于杭州的一家电商经营的公司&#xff0c;做数据开发工程师&#xff0c;工资是20k*14薪&#xff0c;并且是每周三发一次工资。 在大学期间&#xff0c;我选择了学习计算机相关专业&#xff0c;但是课堂上所学的知识常常让我觉得晦涩…

仙境传说RO :ra脚本加载结构和开发语法讲解

仙境传说RO &#xff1a;ra脚本加载结构和开发语法讲解 大家好&#xff0c;我是艾西。上一篇文章中我们聊完了怎么在游戏中新建NPC&#xff0c;感觉还是有不少小伙伴没有太看懂原理。今天艾西给大家深度讲解一下脚本加载结构和开发语法环境文档。 我们最后都是以ra脚本为主要…

提高客户满意度的4种方式

随着技术的使用越来越多&#xff0c;客户体验格局已经永远改变了。长时间的等待时间和缓慢的响应不再被接受&#xff0c;并且对客户满意度产生巨大影响。即时满足和满足客户的高期望至关重要。 那么如何提高客户满意度呢&#xff0c;接下来将为您推荐五种最常见的方法&#xf…

SpringCloud Alibaba Sentinel学习

SpringCloud Alibaba Sentinel 1. Sentinel 使用 第一步、下载Sentinel的jar包&#xff0c;并且在命令行输入 java -jar sentinel-dashboard-1.8.0.jar 启动jar包 第二步、在项目中添加Sentinel依赖 <!--引入 alibaba-sentinel 场景启动器--> <dependency><g…

【每日算法】【171. Excel 表列序号】

☀️博客主页&#xff1a;CSDN博客主页 &#x1f4a8;本文由 我是小狼君 原创&#xff0c;首发于 CSDN&#x1f4a2; &#x1f525;学习专栏推荐&#xff1a;面试汇总 ❗️游戏框架专栏推荐&#xff1a;游戏实用框架专栏 ⛅️点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd;&…

Cookie和session工作流程详解

目录 cookie机制 session会话 理解会话机制 Servlet中对Cookie和Session提供的 HttpServletrequest类中的方法&#xff1a; 模拟实现登录功能 首先实现功能分为两个界面&#xff1a; &#xff08;1&#xff09;登录页面代码&#xff08;前端代码&#xff09; (2) 编写Lo…

docker cgroup资源占用及docker的镜像创建

cgroup用来资源限制 包括cpu&#xff0c;内存&#xff0c;磁盘三大方面 基本复写了常见的资源配额和使用量控制 cgroup是controlgroup的缩写 设置cpu使用率的上限 linux通过cfs&#xff08;完全公平调度器&#xff09;来调度各个进程对cpu的使用&#xff0c;cfs默认的调度…

Maven 介绍,根据 Maven 官方文档整理

这部分内容主要根据 Maven 官方文档整理&#xff0c;做了对应的删减&#xff0c;主要保留比较重要的部分&#xff0c;不涉及实战&#xff0c;主要是一些重要概念的介绍。 Maven 介绍 Maven 官方文档是这样介绍的 Maven 的&#xff1a; Apache Maven is a software project man…

OpenGL 着色器简介

1.简介 着色器(Shader)是运行在GPU上的小程序。这些小程序为图形渲染管线的某个特定部分而运行。从基本意义上来说&#xff0c;着色器只是一种把输入转化为输出的程序。着色器也是一种非常独立的程序&#xff0c;因为它们之间不能相互通信&#xff1b;它们之间唯一的沟通只有通…

Python数据攻略-DataFrame的数据计算和整理

大家好&#xff0c;我是Mr数据杨。今天&#xff0c;我们要踏上一场探索Python的旅程&#xff0c;途中我们将讲解算术运算、NumPy和SciPy函数的应用、DataFrame的排序、过滤、统计和遍历等技巧。想象一下如果《三国演义》中的诸葛亮有了Python的帮助&#xff0c;他将如何更有效地…

java debug调试工具

文章目录 java debug调试工具debugdebug运行断点如何运行 具体使用step intostep into Force step intoresume programstopview breakpointsmute breakpointsstep ourt Shift消除debug java debug调试工具 debug 就是调试工具&#xff0c;用来查看代码在运行工程数据的变化。 …

尚硅谷大数据hadoop教程_yarn

p125 课程介绍 p126 yarn基础架构 YARN主要由ResourceManager、NodeManager、ApplicationMaster和Container等组件构成。 p127 工作机制 &#xff08;1&#xff09;MR程序提交到客户端所在的节点。 &#xff08;2&#xff09;YarnRunner向ResourceManager申请一个Applicatio…

一本书让你彻底搞懂安卓系统性能优化(文末送书5本)

&#x1f935;‍♂️ 个人主页&#xff1a;艾派森的个人主页 ✍&#x1f3fb;作者简介&#xff1a;Python学习者 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4ac;点赞&#x1f4…

c盘清理软件:清理垃圾、扩大c盘和系统迁移

一、为什么要c盘清理软件 Windows系统采用了NTFS文件系统&#xff0c;这种文件系统特点是有文件碎片和系统产生的临时文件会大量存储到系统盘上&#xff0c;而且在使用电脑的过程中&#xff0c;由于程序的安装、升级、卸载和其他操作会产生大量无用的垃圾文件&#xff0c;这些…

文心一言 VS 讯飞星火 VS chatgpt (32)-- 算法导论5.2 4题

四、利用指示器随机变量来解如下的帽子核对问题(hat-heck problem):n位顾客&#xff0c;他们每个人给餐厅核对帽子的服务生一顶帽子。服务生以随机顺序将帽子归还给顾客。请问拿到自己帽子的客户的期望数是多少? 文心一言&#xff1a; 我们可以将这个问题转化为求解在指示器…

Java的Comparator升序降序的记法

在使用Java自带的排序函数时&#xff0c;往往需要根据自己的需求自定义比较器。以前一直对Comparator的升序降序疑惑。现在记录一下&#xff0c;加深下印象。 先给结论&#xff1a; 实现Comparator接口&#xff0c;必须实现下面这个函数&#xff1a; Override public int co…

Vue+springboot电动车共享电池租赁管理系统设计与实现

基于java语言、Springboot框架、B/S架构、Mysql数据库设计并实现了共享电动车电池管理系统设计与实现。系统主要包括首页、个人中心、用户管理、维护人员管理、商户管理、区域信息管理、电池信息管理、租赁订单管理、归还订单管理、费用订单和定、提醒信息管理、维护信息管理、…