Spring启动测试无法加载

时间:2016-11-23 14:08:33

标签: spring spring-boot

我创建了一个非常简单的Spring启动应用程序,我正在使用1.4版本附带的一些新测试功能对其进行测试。

应用程序运行正常,大多数测试也是如此,不包括具有新注释的测试。

@SpringBootTest

我一直得到一个“缺少EmbeddedServletContainerFactory bean”,根据我看到的其他问题是没有以下依赖“spring-boot-starter-web”的问题,但我在我的pom中有这个。

以下是失败的测试代码和我的pom.xml。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DataJpaTest
public class BookControllerIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private BookRepository bookRepository;

    @Test
    public void shouldRetrieveBook(){
        bookRepository.save(new Book("Java"));

        final ResponseEntity<Book> result = restTemplate.getForEntity("/books/{bookName}", Book.class, "Java");

        assertThat(result.getStatusCode(), equalTo(HttpStatus.OK));
        assertThat(result.getBody().getName(), equalTo("Java"));
    }
}

以下是pom。

<?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>

<groupId>com.scottlogic</groupId>
<artifactId>library</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>library</name>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.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>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

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

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

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如评论中所述,删除@DataJpaTest就可以了。