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

@DataMongoTest正在创建空MongoTemplate

公孙慎之
2023-03-14

我一直试图按照下面链接中的说明来尝试添加一个自动配置的嵌入式MongoDB实例用于Cucumber集成测试。这目前是不起作用的,因为我一直得到一个空的MongoTemplate。我以为@DataMongoTest会自动配置“@AutoWired private MongoTemplate MongoTemplate;”事实不是这样吗?下面是我的代码:

@SpringBootTest(classes = AppCommentApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DataMongoTest
public abstract class SpringIntegrationTest {

    @Value("${local.server.port}")
    public int port;

    @Autowired
    private MongoTemplate mongoTemplate;

    protected void importJSON(String collection, String file) {
        try {
            for (String line : FileUtils.readLines(new File(file), "utf8")) {
                Document doc = Document.parse(line);
                mongoTemplate.save(doc, collection);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not import file: " + file, e);
        }
    }

}


@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty",
                 features = "src/test/resources/features",
                 glue = "com.app.comment.cucumber")
public class CucumberIntegrationTest {
}


public class StepDefinitions extends SpringIntegrationTest {

    private Map<String, String> headerMap = null;
    private String postBody = null;
    private String putBody = null;
    private String formData = null;
    private Response response = null;
    private String data = null;

    private final static String MONGODB_COLLECTION = "comment";
    private final static String MONGODB_DATA = "src/test/resources/mongodb-data/data.txt";

    @Before
    public void setup() {
        importJSON(MONGODB_COLLECTION, MONGODB_DATA);
    }

    @Given("^the header information$")
    public void the_header_information(Map<String, String> headerMap) throws Throwable {
        this.headerMap = headerMap;
    }

    @Given("^post message body \"(.*?)\"$")
    public void post_message_body(String postBody) throws Throwable {
        this.postBody = postBody;
    }

    @Given("^put message body \"(.*?)\"$")
    public void put_message_body(String putBody) throws Throwable {
        this.putBody = putBody;
    }
}
<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>

    <groupId>com.app.comment</groupId>
    <artifactId>app-comment-api</artifactId>
    <version>1.0.4</version>
    <packaging>jar</packaging>

    <name>app-comment-api</name>
    <description>App Comments Microservice</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <log4j.version>2.4.1</log4j.version>
        <commons.lang3.version>3.3.2</commons.lang3.version>
        <guava.version>19.0</guava.version>
        <swagger.version>2.4.0</swagger.version>
        <surefire.junit47.version>2.18.1</surefire.junit47.version>
        <rest-assured.version>2.8.0</rest-assured.version>
        <jacoco.version>0.7.5.201505241946</jacoco.version>
        <powermock.version>1.6.4</powermock.version>
        <commons.io.version>2.4</commons.io.version>
        <httpclient.version>4.5.1</httpclient.version>
        <jayway.jsonpath.version>2.2.0</jayway.jsonpath.version>
        <jjwt.version>0.6.0</jjwt.version>
        <docker.image.prefix>app</docker.image.prefix>
        <docker.spotify.plugin.version>0.4.5</docker.spotify.plugin.version>
        <jacoco.maven.plugin.version>0.7.7.201606060606</jacoco.maven.plugin.version>
        <fongo.version>2.0.11</fongo.version>
        <cucumber.version>1.2.5</cucumber.version>
        <gatling.highcharts.version>2.2.3</gatling.highcharts.version>
        <gatling.plugin.version>2.2.1</gatling.plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <!-- Utility -->
        <dependency>
            <groupId>com.logentries</groupId>
            <artifactId>logentries-appender</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons.io.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons.lang3.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>${jayway.jsonpath.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>${jjwt.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.6.5</version>
        </dependency>

        <!-- Test Dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>spring-mock-mvc</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-spring</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.gatling.highcharts</groupId>
            <artifactId>gatling-charts-highcharts</artifactId>
            <version>${gatling.highcharts.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- Package as a docker image -->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>${docker.spotify.plugin.version}</version>
                <configuration>
                    <serverId>docker-hub</serverId>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                    <imageTags>
                        <imageTag>${project.version}</imageTag>
                    </imageTags>
                </configuration>
            </plugin>
            <!-- Runs Code Coverage Reports -->
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco.maven.plugin.version}</version>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/*IntegrationTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
        <id>cucumber-tests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>none</exclude>
                        </excludes>
                        <includes>
                            <!-- Include your Cucumber tests, as an example -->
                            <exclude>**/*IntegrationTest.java</exclude>
                            <exclude>**/*Simulation.scala</exclude>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        </profile>
        <profile>
            <id>gatling-tests</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>io.gatling</groupId>
                        <artifactId>gatling-maven-plugin</artifactId>
                        <version>${gatling.plugin.version}</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>execute</goal>
                                </goals>
                                <configuration>
                                    <simulationClass>com.app.comment.gatling.MicroserviceServiceSimulation</simulationClass>
                                </configuration>
                            </execution>
                        </executions>
                        <configuration>
                            <configFolder>${project.basedir}/src/test/resources</configFolder>
                            <dataFolder>${project.basedir}/src/test/resources/data</dataFolder>
                            <resultsFolder>${project.basedir}/target/gatling/results</resultsFolder>
                            <bodiesFolder>${project.basedir}/src/test/resources/bodies</bodiesFolder>
                            <simulationsFolder>${project.basedir}/src/test/scala</simulationsFolder>
                            <runDescription>This-is-the-run-description</runDescription>
                            <!--    <noReports>false</noReports> -->
                            <!--   <reportsOnly>directoryName</reportsOnly> -->
                            <!--   <simulationClass>foo.Bar</simulationClass> -->
                            <!--   <jvmArgs> -->
                            <!--     <jvmArg>-DmyExtraParam=foo</jvmArg> -->
                            <!--   </jvmArgs> -->
                            <!--    <fork>true</fork> -->
                            <!--    <propagateSystemProperties>true</propagateSystemProperties> -->
                            <!--   <failOnError>true</failOnError> -->
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>

共有1个答案

诸经略
2023-03-14

如果您使用JUnit4,您应该有runwith(SpringRunner.class)。使用JUnit5是不必要的。

并且,@springboottest不能与@datamongotest共存,因为它们是针对应用程序的不同部分,后者只针对数据部分,而前者则针对应用部分。(实际上,如果将这两者放在一起,那么它们的@bootstrapwith将会发生冲突,并且无法启动测试)

@DataMongoTest将使用嵌入式数据库,您不需要执行@AutoWiredMongoTemplate以外的其他配置。如果要使用真正的db,请执行以下操作:

@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
@ActiveProfiles("db")
@DataMongoTest
class CouponTypeRefRepositoryTest {

    @Autowired
    private CouponTypeRefRepository repository; // a simple repository extending `DataMongoRepository`

    @Autowired
    private MongoTemplate mongoTemplate;


    @BeforeEach
    void prepare() {
        CouponTypeRef toSave = CouponTypeRef.builder()
                .id((short)1)
                .duration((short)1)
                .couponType("COMMERCIAL")
                .couponTypeRefConfig(CouponTypeRefConfig.REFUNDABLE_NORMAL)
                .build();
        mongoTemplate.save(toSave, "CouponTypeRef");
    }

    @Test
    void shouldReturnCouponTypeRef() {
        Optional<CouponTypeRef> optional = repository.findById((short)1);
        assertThat(optional.isPresent(), is(true));
        assertThat(optional.get().getCouponType(), is("COMMERCIAL"));
        assertThat(optional.get().getDuration(), is((short)1));
        assertThat(optional.get().getCouponTypeRefConfig(), is(CouponTypeRefConfig.REFUNDABLE_NORMAL));
    }
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive:2.2.1.RELEASE'

db配置文件配置

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: app1

更多信息请访问:https://www.baeldung.com/spring-boot-embedded-mongodbhttps://docs.spring.io/spring-boot/docs/1.5.4.release/reference/html/boot-features-testing.html

 类似资料:
  • 嗨,我是Android开发和使用Android Studio的新手。我需要创建*.aar lib。我创建了新的Android库项目(目前为空)。如何从中生成*.aar文件?你能按步骤解释吗?读过很多题目但还是不成功。多谢了。

  • 我正在开发一个java应用程序来创建elasticSearch索引。索引目前每周在一台开发机器上构建,集群在其他(测试和prod)机器上的现有集群上手动复制。新的方案仍然包括每周从头开始重建指数。 我正在使用5.6.3和Low-High level rest客户端进行更新。经过一些初步的调查(并得到相当多的帮助),我的目标是去一个2(或3)阶段的开发使用别名。 首先,我将在dev上为现有索引(es

  • 点击“产品”标签中的“函数计算”,进入函数计算工作空间列表页,在创建空间前请先以管理员账号登录生态云,确保有创建空间的权限,点击“创建新空间”,输入名称及描述。

  • 我正在尝试使用JPA将表映射到类 现在,当hibernate连接到数据库时,它正在创建一个名为no_of_firms_has_bad_debt_in_last_3_years_Including_credit_card的新列,而不是将其映射到现有列(firms_bad_dt_in_last)。我错过什么了吗? 我不想创建一个新列,我想让它映射到现有列并从中获取数据…我该怎么做呢?谢谢! 我用的是s

  • 问题内容: 我将CloudFlare用于我的一个高流量网站,它位于堆栈的前面。 关键是CloudFlare除了创建新的连接之外,还保留空闲连接,这不是我可以更改的设置。 当我让Varnish或Nginx坐在前面监听端口80时,它们具有开箱即用的配置来挂断空闲连接。 很好,直到我必须将用Go编写的代理添加到堆栈的最前面。它使用标准库。 我不是Go向导,而是根据人们告诉我的内容,只有读写超时设置,而不

  • 问题内容: 我想在UITextField的开头保留一些空间,就像这里:向UITextField添加左侧边距 但是我不知道如何用Swift做到这一点。 问题答案: 这就是我现在正在使用的: 斯威夫特4.2 斯威夫特4 斯威夫特3: 我从未设置其他填充,但是您可以进行调整。此类不会处理textfield上的rightView和leftView。如果您希望它得到正确处理,则可以使用类似(objc中的示例