[JAVA] Overwrite the contents of config with Spring-boot + JUnit5

Introduction

You can use it immediately if you use Mockito, but I wrote it because I wanted to make a note.

environment

Java9 Spring-boot 2.0.0.RELEASE

This goal

Rewrite the Config set in the Service class from Junit instead of reading the test Config file.

pom.xml It is written in other articles, but I will always check it, so I will write it in the meantime.

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.tasogarei</groupId>
	<artifactId>junit-test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>junit-test</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>9</java.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>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>1.0.1</version>
            <scope>test</scope>
        </dependency>
	</dependencies>

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


</project>

Service There is a mysterious private method, but I just want to try something else after this. please do not worry.

package com.tasogarei.app.service;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tasogarei.app.util.TestConfig;

@Service
public class TestService {
    
    @Autowired
    private TestConfig config;
    
    public String getString() {
        return getStr();
    }
    
    private String getStr() {
        return config.getTest();
    }    
}

config This time, we will do it based on the Configuration annotation.

package com.tasogarei.app.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfig {
    @Value("${app.test}") 
    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

application.properties


app.test=configtest

Put an appropriate value in ╩╗application.properties`.

Test class

If you convert it to Mock with @ MockBean and do the content you want to rewrite withMockito.when (). Then (), the one that was converted to Mock in the test will be used, so this is okay. Even if the return value of the method specified by when is a class, if you put the class you want to rewrite with then, that class will be used, so you can test with it. Of course the types must be the same.

package com.tasogarei.app.service;

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

import java.util.Properties;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.tasogarei.app.util.TestConfig;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class TestServiceTest {

    @Autowired
    private TestService testService;
    
    @MockBean
    private TestConfig testConfig;
    
    @Test
    public void test() {
        Mockito.when(testConfig.getTest()).thenReturn("hogehoge123");
        assertEquals(testService.getString(), "hogehoge123");
    }
}

Finally

I feel that rewriting with the test method is subtle, so I think that it is better to do what can be done in advance processing there.

Recommended Posts

Overwrite the contents of config with Spring-boot + JUnit5
Test the contents of an Excel file with JUnit
Check the contents of params with pry
Format the contents of LocalDate with DateTimeFormatter
Verify the contents of the argument object with Mockito
List the contents of categories created with Active Hash
[JUnit5] Dealing with "the reference of assertEquals is ambiguous"
Change the port with SpringBoot
UnitTest with SpringBoot + JUnit + Mockito
[Rails] Check the contents of the object
Replace the contents of the Jar file
The basics of SpringBoot + MyBatis + MySQL
[Ruby] Display the contents of variables
Try Hello World with the minimum configuration of Heroku Java spring-boot
Overwrite upload of file with the same name with BOX SDK (java)
Check the contents of the Java certificate store
Memo: [Java] Check the contents of the directory
Folding and unfolding the contents of the Recyclerview
[Ruby] Cut off the contents of twitter-ads
Check the processing contents with [rails] binding.pry
Using SSIServlet with built-in Tomcat of SpringBoot 2.2.4
About the treatment of BigDecimal (with reflection)
The contents of the data saved by CarrierWave.
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
After all I wanted to preview the contents of mysql with Docker ...
JAVA: jar, aar, view the contents of the file
Customize how to divide the contents of Recyclerview
Easy JUnit test of Elasticsearch 2018 version with embedded-elasticsearch
Manage the version of Ruby itself with rbenv
The story of tuning android apps with libGDX
I want to var_dump the contents of the intent
Calculate the similarity score of strings with JAVA
Prepare the environment of CentOS 8 with Sakura VPS
Specify the default value with @Builder of Lombok
Measure the distance of the maze with breadth-first search
I checked the number of taxis with Ruby
[Docker] How to see the contents of Volumes. Start a container with root privileges.
Let's implement a function to limit the number of access to the API with SpringBoot + Redis
[Swift] Get the number of steps with CMP edometer
Error when starting JUnit with deprecated version of POI
I examined the life cycle of the extension of JUnit Jupiter
JavaFX --Match the size of ImageView with other nodes
Get the name of the test case in the JUnit test class
Access the built-in h2db of spring boot with jdbcTemplate
The story of making a reverse proxy with ProxyServlet
Monitor the internal state of Java programs with Kubernetes
Implement the UICollectionView of iOS14 with the minimum required code.
Check the behavior of Java Intrinsic Locks with bpftrace
Personal summary of the guys often used in JUnit 4
WebAPI unit test and integration test with SpringBoot + Junit5, 4 patterns
[Rails] How to get the contents of strong parameters
Check the result of generic parameter inference with JShell
Java: Use Stream to sort the contents of the collection
Roughly the flow of web application development with Rails.
Control the processing flow of Spring Batch with JavaConfig.
I want to be aware of the contents of variables!
The story of making dto, dao-like with java, sqlite
Replace only part of the URL host with java
I want to recreate the contents of assets from scratch in the environment built with capistrano