使用内存数据库为 Rest 控制器编写测试 [英] Use in-memory db to write tests for Rest controllers
问题描述
我正在为 Spring boot Rest 控制器编写测试.这个休息控制器将一些值写入数据库.
I'm writing a test for a Spring boot Rest controller. This rest controller writes some values to the db.
我想使用 Spring 为这个测试提供的内存数据库.根据 this doc 我必须使用 @DataJpaTest
注释测试类,这会导致此错误:
I want to use in-memory database which Spring provides for this test. According to this doc I have to annotate the test class with @DataJpaTest
, which causes this error:
java.lang.IllegalStateException: Failed to load ApplicationContext
在错误堆栈跟踪的更深处,我看到抛出了以下异常:
Further down in the error stack trace I see the following exception was thrown:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration"的bean时出错:通过构造函数参数0表达的不满足的依赖;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为dataSource"的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.IllegalStateException: Failed to replace DataSource with an Embedded database for tests.如果你想要一个嵌入式数据库,请在类路径上放置一个支持的数据库或调整@AutoconfigureTestDatabase 的替换属性.
这是我正在研究的测试类:
This is the test class which I'm working on:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@DataJpaTest
public class AuthenticationControllerFTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private AuthenticationManager authenticationManager;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain).build();
}
@Test
public void testCreate() throws Exception {
String exampleUserInfo = "{\"name\":\"Salam12333\",\"username\":\"test@test1.com\",\"password\":\"Salam12345\"}";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/signup")
.accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
int status = response.getStatus();
Assert.assertEquals("http response status is wrong", 200, status);
}
}
是什么导致了这个错误?
What is causing this error ?
编辑 1这是我的 application.properties
的内容:
spring.datasource.username = hello
spring.datasource.password = hello
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/myproject?useSSL=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
logging.level.org.springframework.web=DEBUG
server.port = 8443
server.ssl.key-store = classpath:tomcat.keystore
server.ssl.key-store-password = hello
server.ssl.key-password = hello
server.ssl.enabled = true
server.ssl.key-alias=myproject
编辑 2
我在 pom.xml
中添加了以下内容:
I added the following to my pom.xml
:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
我使用以下内容创建了 application-test.properties
:
I created application-test.properties
with the following content:
spring.datasource.username= root
spring.datasource.password= password
spring.datasource.driver-class-name= org.h2.Driver
spring.datasource.url= jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
- 用户名和密码是什么?我应该在哪里设置它们?
- 我还在测试类中添加了
@ActiveProfiles("test")
,当我运行测试时,我收到一个包含这一行的错误:
- What is the username and passowrd ? Where should I set them ?
- I also added
@ActiveProfiles("test")
to the test class, when I run the test I get an error which includes this line :
Caused by: org.hibernate.HibernateException: 'hibernate.dialect' 未设置时,对 DialectResolutionInfo 的访问不能为空
推荐答案
假设您使用 @SpringBootApplication
注释类,它启用自动配置并且您有 H2
依赖于类路径(见下文) Spring Boot
将看到 H2
内存数据库依赖项,它将创建 javax.sql.DataSource
实现.默认连接 URL 为 jdbc:h2:mem:testdb
,默认用户名和密码为:用户名:sa 和密码:空.
Assuming you annotate class with @SpringBootApplication
, which enables auto-configuration and you have H2
dependency on classpath(see below) Spring Boot
will see H2
in-memory database dependency and it will create javax.sql.DataSource
implementation. Default connection URL is jdbc:h2:mem:testdb
and the default username and password are: username: sa and password: empty.
application.properties 文件
application.properties file
spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.h2.console.enabled=true // if you need console
H2 依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency> // If you need h2 web console
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
您可以访问 h2 控制台进行管理 http://localhost:8080/h2-console
You can gain access to h2 console for management http://localhost:8080/h2-console
这篇关于使用内存数据库为 Rest 控制器编写测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!