当前位置: 首页 > 知识库问答 >
问题:

如何在使用Junit 5的Spring boot 2.1.0.M4中使用@DatajPatest测试Spring CrudRepository

马魁
2023-03-14

我不能使用spring boot 2.1.0.M4和Junit5和@datajpatest测试我的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 Version2.0.3.Release中运行良好。我可以从发布说明(https://github.com/spring-projects/spring-boot/wiki/spring-boot-2.1.0-M2-release-notes)中看到引入了引导模式。这可能会导致问题,也可能不会导致问题。

共有1个答案

鲁弘厚
2023-03-14

不要将@springboottest@datajpatest混用

可以从Javadoc中读到:

注释,可与{@code@runwith(Springrunner.class)}结合使用,用于典型的JPA测试。可以在测试只关注JPA组件时使用。

对于完全集成测试,您应该使用@springboottest

如果您希望加载完整的应用程序配置,但使用嵌入式数据库,则应考虑将{@link SpringBootTest@SpringBootTest}与{@link AutoConfigureTestDatabase@AutoConfigureTestDatabase}结合使用,而不是使用此注释。

 类似资料:
  • 问题内容: 如何在Mockito和JUnit 5中使用注入? 在JUnit4中,我可以只使用Annotation。在JUnit5中没有注释吗? 问题答案: 有多种使用Mockito的方法-我将一一介绍。 手动地 无论JUnit版本是什么(或测试框架),都可以使用Works手动创建模拟。 基于注释 使用@Mock -annotation和相应的调用 来创建嘲笑的作品无论JUnit版本(或测试框架,对

  • 如何使用Mockito和JUnit 5的注射? 在JUnit4中,我可以只使用注释。JUnit5中没有注释吗?

  • 如何使用JUnit5测试抛出NullPointerException的方法。但是我在方法中捕获到了这个异常,因此test以错误结尾:“Expected java.lang.NullPointerException to be thrown,But nothing was thrown”。 谢谢

  • Web上使用Neo4j进行Spring集成测试的大多数示例仍然在JUnit4上,并且使用Neo4JRule。 我们如何为Neo4j+Spring+JUnit5创建一个设置?

  • 使用Gradle及其JUnit4支持,我可以使用选项选择特定的测试,如下所示: 在使用JUnit5 Gradle任务时,此选项无效。当从命令行使用任务时,它会被无人值守地忽略。真正的工作是由完成的,它不支持以下选项: JUnit5插件支持选择特定的测试吗?