Java 如何在没有db连接的情况下在Spring中正确运行所有Junit测试
嗨,朋友们,希望你们一切顺利 所以我正在为我的简单项目编写一些简单的单元测试,当我开始运行测试时,我遇到了一些问题 首先是测试代码: GetAllUsersServiceTest.javaJava 如何在没有db连接的情况下在Spring中正确运行所有Junit测试,java,spring,spring-boot,junit,Java,Spring,Spring Boot,Junit,嗨,朋友们,希望你们一切顺利 所以我正在为我的简单项目编写一些简单的单元测试,当我开始运行测试时,我遇到了一些问题 首先是测试代码: GetAllUsersServiceTest.java package com.challenge.simpleApi.domains.users.services.getAllUsersService; import com.challenge.simpleApi.domains.users.models.Users; import com.challenge
package com.challenge.simpleApi.domains.users.services.getAllUsersService;
import com.challenge.simpleApi.domains.users.models.Users;
import com.challenge.simpleApi.domains.users.repositories.UsersRepository;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
@ExtendWith(MockitoExtension.class)
public class GetAllUsersServiceTest {
@Mock
private UsersRepository usersRepository;
@InjectMocks
private GetAllUsersService getAllUsersService;
private List<Users> fakeRepositoryReturn = new ArrayList<Users>();
final Users user1 = new Users(1L, "John", 28, null);
final Users user2 = new Users(2L, "Peter", 20, null);
final Users user3 = new Users(3L, "Patricia", 21, null);
@BeforeEach
void setUp() {
fakeRepositoryReturn.add(user1);
fakeRepositoryReturn.add(user2);
fakeRepositoryReturn.add(user3);
}
@Test
@DisplayName("Should be able to return all Users")
void ShouldReturnAllUsers() {
Mockito.when(usersRepository.findAll()).thenReturn(fakeRepositoryReturn);
List<Users> actual = getAllUsersService.execute();
Assertions.assertEquals(fakeRepositoryReturn, actual);
}
}
package com.challenge.simpleApi.domains.users.services.CreateUsersService;
import com.challenge.simpleApi.domains.users.models.Users;
import com.challenge.simpleApi.domains.users.repositories.UsersRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.bind.MethodArgumentNotValidException;
//@SpringBootTest
//@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
@ExtendWith(MockitoExtension.class)
public class CreateUsersServiceTest {
@Mock
private UsersRepository usersRepository;
@InjectMocks
private CreateUsersService createUsersService;
//Validator Instances - Used to validate the annotations inside the entities
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeEach
void setUp() {}
@BeforeAll
static void beforeAll() {
//Instantiate the validators
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@AfterAll
static void afterAll() {
validatorFactory.close();
}
@Test
@DisplayName("Should be able to create a new User")
void createUserTest() {
Users userInput = new Users(null, "Jonas", 28, null);
Users expected = new Users(1L, "Jonas", 28, null);
Mockito.when(usersRepository.save(userInput)).thenReturn(expected);
Users actual = createUsersService.execute(userInput);
Assertions.assertEquals(expected, actual);
}
@Test
@DisplayName("Should not be able to create a new User without a name")
void CreateUserWithoutNameTet() {
Users userInput = new Users(null, null, 18, null);
Set<ConstraintViolation<Users>> violations = validator.validate(userInput);
List<String> errors = new ArrayList<String>();
errors =
violations.stream().map(x -> x.getMessage()).collect(Collectors.toList());
Assertions.assertEquals("Name should not be empty", errors.get(0));
}
@Test
@DisplayName("Should not be able to create a new under 18yo User")
void CreateUnder18User() {
Users userInput = new Users(null, "Paull", 17, null);
var errors = validator
.validate(userInput)
.stream()
.map(x -> x.getMessage())
.collect(Collectors.toList());
Assertions.assertEquals("Should not be less than 18", errors.get(0));
}
}
但是,当我运行所有这些测试时,我的测试都会出错:
mvn test
它看起来像是在连接数据库。老实说,我不知道如何才能改变这种行为。它们各自运行得相当好,但是当我运行它们所有ta一次时,事情开始变得奇怪
如果你们能帮我了解出了什么问题,我会很感激的
提前谢谢
这是错误堆栈:
2021-01-31 14:18:45.328 INFO 17704 --- [ main] c.c.simpleApi.SimpleApiApplicationTests : Starting SimpleApiApplicationTests using Java 15.0.2 on DESKTOP-AO5BOC0 with PID 17704 (started by matt in /home/matt/Source/java/simpleApi)
2021-01-31 14:18:45.333 INFO 17704 --- [ main] c.c.simpleApi.SimpleApiApplicationTests : No active profile set, falling back to default profiles: default
2021-01-31 14:18:46.114 INFO 17704 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-01-31 14:18:46.158 INFO 17704 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 38 ms. Found 2 JPA repository interfaces.
2021-01-31 14:18:46.689 INFO 17704 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-01-31 14:18:46.724 INFO 17704 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.27.Final
2021-01-31 14:18:46.752 INFO 17704 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-01-31 14:18:46.827 INFO 17704 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-01-31 14:18:47.877 ERROR 17704 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
[...]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98) ~[postgresql-42.2.18.jar:42.2.18]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213) ~[postgresql-42.2.18.jar:42.2.18]
... 135 common frames omitted
2021-01-31 14:18:47.929 WARN 17704 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
[...]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
... 118 common frames omitted
2021-01-31 14:18:47.981 ERROR 17704 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@a6a66fac] to prepare test instance [com.challenge.simpleApi.SimpleApiApplicationTests@a25870b7]
java.lang.IllegalStateException: Failed to load ApplicationContext
[...]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.376 s <<< FAILURE! - in com.challenge.simpleApi.SimpleApiApplicationTests
[ERROR] contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] SimpleApiApplicationTests.contextLoads » IllegalState Failed to load Applicati...
[ERROR] CreateUsersServiceTest.CreateUnder18User:71 NullPointer Cannot invoke "javax.v...
[ERROR] CreateUsersServiceTest.CreateUserWithoutNameTet:56 NullPointer Cannot invoke "...
[INFO]
[ERROR] Tests run: 5, Failures: 0, Errors: 3, Skipped: 0
[INFO]
2021-01-31 14:18:45.328信息17704-[main]c.c.simpleApi.simpleApi应用程序测试:在桌面-AO5BOC0上使用Java 15.0.2启动SimpleApp应用程序测试,PID 17704(由matt在/home/matt/Source/Java/simpleApi中启动)
2021-01-31 14:18:45.333信息17704---[main]c.c.simpleApi.simpleApi应用程序测试:未设置活动配置文件,返回默认配置文件:默认
2021-01-31 14:18:46.114信息17704---[main].s.d.r.c.RepositoryConfigurationDelegate:在默认模式下引导Spring数据JPA存储库。
2021-01-31 14:18:46.158信息17704---[main].s.d.r.c.RepositoryConfigurationDelegate:在38毫秒内完成了Spring数据存储库扫描。找到了2个JPA存储库接口。
2021-01-31 14:18:46.689信息17704---[main]o.hibernate.jpa.internal.util.LogHelper:hh000204:正在处理PersistenceUnitInfo[名称:默认值]
2021-01-31 14:18:46.724信息17704---[main]org.hibernate.Version:hh000412:hibernate ORM核心版本5.4.27.Final
2021-01-31 14:18:46.752信息17704---[main]o.hibernate.annotations.common.Version:HCANN000001:hibernate Commons annotations{5.1.2.Final}
2021-01-3114:18:46.827信息17704---[main]com.zaxxer.hikari.HikariDataSource:hikaripol-1-开始。。。
2021-01-31 14:18:47.877错误17704---[main]com.zaxxer.hikari.pool.HikariPool:HikariPool-1-池初始化期间出现异常。
org.postgresql.util.PSQLException:与本地主机的连接被拒绝:5432。检查主机名和端口是否正确,邮政局长是否接受TCP/IP连接。
[...]
在org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(connectionfactorympl.java:98)~[postgresql-42.2.18.jar:42.2.18]
在org.postgresql.core.v3.connectionfactorympl.openConnectionImpl(connectionfactorympl.java:213)~[postgresql-42.2.18.jar:42.2.18]
... 省略135个公共帧
2021-01-31 14:18:47.929警告17704---[main]o.h.e.j.e.i.JdbcEnvironmentInitiator:HH000342:无法获得查询元数据的连接
org.postgresql.util.PSQLException:与本地主机的连接被拒绝:5432。检查主机名和端口是否正确,邮政局长是否接受TCP/IP连接。
[...]
在org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
... 省略118个公共帧
2021-01-31 14:18:47.981错误17704---[main]o.s.test.context.TestContextManager:在允许TestExecutionListener[org.springframework.test.context.web]时捕获异常。ServletTestExecutionListener@a6a66fac]准备测试实例[com.challenge.simpleApi]。SimpleApiApplicationTests@a25870b7]
java.lang.IllegalStateException:未能加载ApplicationContext
[...]
[错误]测试运行:1,失败:0,错误:1,跳过:0,所用时间:3.376秒
15
org.mapstruct
mapstruct处理器
${org.mapstruct.version}
org.projectlombok
龙目
${org.projectlombok.version}
org.projectlombok
lombok映射结构绑定
${lombok mapstruct binding.version}
先谢谢你!:) 这个答案最初由@deadpool在评论中发布 Spring初始值设定项在测试包中创建一个示例测试类。此类具有@SpringBootTest注释 此注释确保在测试中加载完整的Spring引导环境,需要连接
这种情况的解决方案是删除注释,或者删除java文件本身。这是个好问题,我也很好奇。。。但是无论如何,您可以使用
testcontainers
…@k-wasilewski Hi-friend来模拟连接,谢谢您的提示。我也读过关于testcontainers的文章,它们看起来很强大,但在这个特定的例子中,它们就像是一个“滥杀”,不是吗?谢谢:)你在pom.xml中使用的junit版本是什么?试着将它添加到每个测试类@DirtiesContext(classMode=DirtiesContext.classMode.BEFORE_each_test_方法)如果我们查看日志,这个特殊的测试类SimpleApplicationTests
正在尝试连接数据库,看起来像是集成测试用例@MattV
2021-01-31 14:18:45.328 INFO 17704 --- [ main] c.c.simpleApi.SimpleApiApplicationTests : Starting SimpleApiApplicationTests using Java 15.0.2 on DESKTOP-AO5BOC0 with PID 17704 (started by matt in /home/matt/Source/java/simpleApi)
2021-01-31 14:18:45.333 INFO 17704 --- [ main] c.c.simpleApi.SimpleApiApplicationTests : No active profile set, falling back to default profiles: default
2021-01-31 14:18:46.114 INFO 17704 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-01-31 14:18:46.158 INFO 17704 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 38 ms. Found 2 JPA repository interfaces.
2021-01-31 14:18:46.689 INFO 17704 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-01-31 14:18:46.724 INFO 17704 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.27.Final
2021-01-31 14:18:46.752 INFO 17704 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-01-31 14:18:46.827 INFO 17704 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-01-31 14:18:47.877 ERROR 17704 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
[...]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98) ~[postgresql-42.2.18.jar:42.2.18]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213) ~[postgresql-42.2.18.jar:42.2.18]
... 135 common frames omitted
2021-01-31 14:18:47.929 WARN 17704 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
[...]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
... 118 common frames omitted
2021-01-31 14:18:47.981 ERROR 17704 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@a6a66fac] to prepare test instance [com.challenge.simpleApi.SimpleApiApplicationTests@a25870b7]
java.lang.IllegalStateException: Failed to load ApplicationContext
[...]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.376 s <<< FAILURE! - in com.challenge.simpleApi.SimpleApiApplicationTests
[ERROR] contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] SimpleApiApplicationTests.contextLoads » IllegalState Failed to load Applicati...
[ERROR] CreateUsersServiceTest.CreateUnder18User:71 NullPointer Cannot invoke "javax.v...
[ERROR] CreateUsersServiceTest.CreateUserWithoutNameTet:56 NullPointer Cannot invoke "...
[INFO]
[ERROR] Tests run: 5, Failures: 0, Errors: 3, Skipped: 0
[INFO]
<?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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.challenge</groupId>
<artifactId>simpleApi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>simpleApi</name>
<description>A simple api made crafted with spring</description>
<properties>
<java.version>15</java.version>
<org.mapstruct.version>1.4.1.Final</org.mapstruct.version>
<org.projectlombok.version>1.18.16</org.projectlombok.version>
<lombok-mapstruct-binding.version>0.2.0</lombok-mapstruct-binding.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>15</source> <!-- depending on your project -->
<target>15</target> <!-- depending on your project -->
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>${lombok-mapstruct-binding.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>