如何使用Junit 5在Spring Boot 2.1.0.M4中使用@DataJpaTest测试Spring CrudRepository

我无法使用带有Junit5和@DataJpaTest的spring boot 2.1.0.M4测试spring crud存储库.
我正在使用以下spring crud存储库接口.

@Repository
public interface DestinationRepository extends CrudRepository<Destination, String> {

    Optional<Destination> findCityCode(String code, String cityIsolci);

}

这是我的单元测试课

package com.test.repository;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.test.Destination;

import java.util.Optional;

import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
// @ExtendWith(SpringExtension.class)
public class DestinationRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private DestinationRepository destinationRepository;

    @Test
    public void whenfindByCodeAndCityIsolciThenReturnDestination() throws Exception {
        this.entityManager.persist(new Destination("DXB", "Y", "Dubai gate comment"));

        Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");

        Assert.assertTrue(found.isPresent());

        // assertThat(user.getVin()).isEqualTo("1234");
    }

    // @Test
    // public void whenfindByCodeAndCityIsolciThenReturnDestination() {
    // // given
    // Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
    //
    // // when
    // Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");
    //
    // // then
    // Assert.assertTrue(found.isPresent());
    // Assert.assertEquals(found.get().getGateComment(), dubai.getGateComment());
    // }

    // @Test
    // public void shouldFindAllDestinations() {
    // Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
    // Destination syd = destinationRepository.save(new Destination("SYD", "Y", "SYD gate comment"));
    //
    // Iterable<Destination> destinations = destinationRepository.findAll();
    //
    // assertThat(destinations).hasSize(2).contains(dubai, syd);
    // }

}

这是我的POM.xml

<?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>
    <parent>
        <groupId>***.***.***</groupId>
        <artifactId>******</artifactId>
        <version>1.0.0</version>
        <relativePath />
        <!-- lookup parent from repository -->
    </parent>
    <artifactId>*****</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>${project.artifactId}</name>
    <description>TEST</description>

    <prerequisites>
        <maven>${maven.version}</maven>
    </prerequisites>

    <properties>
        <start-class>c*.*.Application</start-class>
        <junit.jupiter.version>5.2.0</junit.jupiter.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-rsa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Sql server driver -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>

        <!-- Lombok dependencies -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Commons dependencies -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
        </dependency>

        <!-- Logging dependencies -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
        </dependency>

        <!-- Swagger dependencies -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-bean-validators</artifactId>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.vaadin.external.google</groupId>
                    <artifactId>android-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Spring REST Docs dependencies -->
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-webtestclient</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-asciidoctor</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Auto REST Docs dependencies -->
        <dependency>
            <groupId>capital.scalable</groupId>
            <artifactId>spring-auto-restdocs-core</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- JUnit Jupiter API and Engine -->

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>mockwebserver</artifactId>
            <version>3.10.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-test -->
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <version>3.1.8.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mock-server</groupId>
            <artifactId>mockserver-netty</artifactId>
            <version>5.4.1</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                </includes>
                <excludes>
                    <exclude>**/*.jks</exclude>
                </excludes>
            </resource>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.jks</include>
                </includes>
                <excludes>
                    <exclude>**/*.xml</exclude>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.yml</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>com.github.ekryd.sortpom</groupId>
                <artifactId>sortpom-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <configuration>
                    <excludeFromFailureFile>${project.basedir}/exclude-pmd.properties</excludeFromFailureFile>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
            </plugin>
            <plugin>
                <groupId>org.gaul</groupId>
                <artifactId>modernizer-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
            </properties>
        </profile>
        <profile>
            <id>qa</id>
            <properties>
                <spring.profiles.active>qa</spring.profiles.active>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
            </properties>
        </profile>
        <profile>
            <id>eclipse</id>
            <dependencyManagement>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-launcher</artifactId>
                        <version>1.1.1</version>
                        <scope>test</scope>
                    </dependency>
                </dependencies>
            </dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-launcher</artifactId>
                </dependency>

            </dependencies>
        </profile>
    </profiles>

</project>

我只想知道什么是正确的批注才能成功运行测试.
我尝试使用不同的组合

@DataJpaTest
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ExtendWith(SpringExtension.class)

如果我只使用@DataJpaTest和@RunWith(SpringRunner.class)
我收到以下错误:

    [ERROR] whenfindByCodeAndCityIsolciThenReturnDestination  Time elapsed: 1.237 s  <<< ERROR!
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
        at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
        at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: EK_DESTINATIONS in statement [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]
        at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: EK_DESTINATIONS
        at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)

附:只想说这在Spring Boot 2.0.3.RELEASE中工作得很好.
从发行说明(https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1.0-M2-Release-Notes)中可以看到引入了引导模式.这可能会或可能不会导致问题.

解决方法:

不要将@SpringBootTest与@DataJpaTest混合使用

从JavaDoc可以读取:

Annotation that can be used in combination with {@code
@RunWith(SpringRunner.class)} for a typical JPA test. Can be used
when a test focuses only on JPA components.

对于完整的集成测试,您应该使用@SpringBootTest

If you are looking to load your full application configuration, but use an embedded database, you should consider {@link SpringBootTest
@SpringBootTest} combined with {@link AutoConfigureTestDatabase
@AutoConfigureTestDatabase} rather than this annotation.

上一篇:Springboot 2.x 单元测试 JUnit 5


下一篇:Junit5单元测试的常用注解