Java单元测试学习(一)

Java单元测试学习(一)

使用TestContainer和docker结合启动redis

前提

  • docker环境

目录结构

Java单元测试学习(一)_第1张图片

依赖—这里有个小插曲

配置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就不会出现报错


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.6version>
        <relativePath/> 
    parent>
    <groupId>com.atguigugroupId>
    <artifactId>redis_springbootartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>redis_springbootname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>

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

        
        <testcontainers.version>1.15.3testcontainers.version>

        
        <commons.version>2.9.0commons.version>

        
        <lombok.version>1.18.12lombok.version>

    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.testcontainersgroupId>
            <artifactId>testcontainersartifactId>
            <version>${testcontainers.version}version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.testcontainersgroupId>
            <artifactId>junit-jupiterartifactId>
            <version>${testcontainers.version}version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-pool2artifactId>

        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>${lombok.version}version>
            <scope>providedscope>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            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后可查看到启动的容器
    Java单元测试学习(一)_第2张图片

  • 测试通过
    Java单元测试学习(一)_第3张图片

你可能感兴趣的:(实习,测试,java,单元测试,学习,测试工具)