Java 使Spring JUnit测试在测试数据库上运行

Java 使Spring JUnit测试在测试数据库上运行,java,hibernate,spring-mvc,spring-boot,junit,Java,Hibernate,Spring Mvc,Spring Boot,Junit,我想将我的JUnit测试配置为在与应用程序运行的数据库不同的数据库上运行。我已经做了几个小时了,但到目前为止还没有成功。尝试使用application.properties文件和spring配置文件对其进行配置,但没有任何效果。那么如何才能做到这一点呢?任何帮助都将不胜感激 这是我的测试文件: @RunWith(SpringRunner.class) @SpringBootTest(properties = "spring.profiles.active=test") public class

我想将我的JUnit测试配置为在与应用程序运行的数据库不同的数据库上运行。我已经做了几个小时了,但到目前为止还没有成功。尝试使用application.properties文件和spring配置文件对其进行配置,但没有任何效果。那么如何才能做到这一点呢?任何帮助都将不胜感激

这是我的测试文件:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class TestContactController extends AbstractTest {

    @Autowired
    private MockMvc mvc;

    @Test
    @Rollback
    public void testAddContact() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/contact/add").contentType(MediaType.APPLICATION_JSON)
            .content("{\n" +
                    "\t\"authCode\": \"daca824a0bf04d038543373adfdb2c8f\",\n" +
                    "\t\"requestData\":{\n" +
                    "\t\t\"firstName\": \"Max\",\n" +
                    "\t\t\"lastName\": \"Mustermann\",\n" +
                    "\t\t\"category\": {\n" +
                    "\t\t\t\"id\": " + categoryId + "\n" +
                    "\t\t}, \"partOfOrgUnit\": {\n" +
                    "\t\t\t\"id\": " + companyId + "\n" +
                    "\t\t}\n" +
                    "\t}\n" +
                    "}"))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo("{\"success\":true,\"message\":\"SUCCESS: Contact added successfully\"}")));
    }
}
我的持久性xml,包含两个数据库:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         version="2.0">
    <persistence-unit name="sab_pu">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3307/projectdb?serverTimezone=UTC"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="javax.persistence.validation.mode" value="NONE"/>
        </properties>
    </persistence-unit>
    <persistence-unit name="sab_test_pu">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3307/testdb?serverTimezone=UTC"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="javax.persistence.validation.mode" value="NONE"/>
        </properties>
    </persistence-unit>
</persistence>
例外情况:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.SAB.test.testsController.TestContactController':
Unsatisfied dependency expressed through field 'mvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. 
Dependency annotations:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

你有可能使用弹簧靴吗?它还为您提供了一个基于Servlet的“普通”部署到现有Tomcat实例中。我最后一次简单的春季训练太费时了

我可以给你一个Nikos answer和Spring Boot的例子,并假设你正在使用Maven

在Spring Boot中,可以使用
application.properties
文件配置大多数内容。这还包括
persistence.xml
文件的设置

对于您的生产环境,在
src>main>resources
中创建一个
application.properties
文件,其内容如下所示

spring.datasource.url=jdbc:mysql://localhost:3307/projectdb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.show-sql=true
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
@AutoConfigureMockMvc
public class MeTest {
    @Test
    public void testMe() {
        System.out.println("Hello World!");
    }
}
测试环境需要一个名为
application test.properties
且包含此内容的文件

spring.datasource.url=jdbc:mysql://localhost:3307/testdb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
正如您所见,对于
test
ing,您不需要重复所有内容,只需要重复更改的内容

现在,只需启动应用程序,即可测试应用程序以生产模式运行。在控制台中,您应该看到SpringBoot使用MySQL。如果要使用测试设置,请将
-Dspring.profiles.active=test
添加为JVM参数

完成这些步骤后,让我们切换到您的JUnit测试,如下所示

spring.datasource.url=jdbc:mysql://localhost:3307/projectdb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.show-sql=true
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
@AutoConfigureMockMvc
public class MeTest {
    @Test
    public void testMe() {
        System.out.println("Hello World!");
    }
}
@SpringBootTest
将当前配置文件设置为
test
,并启动JUnit测试运行


这只是解决问题的一种可能的方法。我希望它能帮助您,并且一切正常,因为我的工作机器上没有MySQL数据库。

如上所述,我尝试过,但它忽略了.properties文件中的设置。我不太确定。我对此有点陌生,我想使用MocMvc来执行我的rest请求。通过删除@AutoConfigure,它将不再工作。我应该自己配置它而不是让spring为我配置吗?好的,但是我该如何配置它呢?我使用spring Boot并按照您的建议进行了配置,但是在删除“@AutoConfigureMockMvc”注释后,我得到了以下异常(见编辑的问题)。我应该如何配置mockmvc?如果将
@AutoConfigureMockMvc
添加到JUnit测试中,它会工作吗?我更新了我的example.nope,如果我加上它不再在测试数据库上运行,我实现了一个quick and dirty示例,其中我使用H2数据库进行测试。在本例中,我能够使用Spring数据存储实体,并使用MockMvc调用REST服务,您是否使用我的
应用程序.properties
示例来配置数据库?好的,我根据我的控制器配置了MockMvc,它工作了。非常感谢!