缺少@SpringBootTest中的EmbeddedServletContainerFactory

时间:2016-12-20 08:04:11

标签: spring-boot

您好我已经写了一个测试,看起来像这样

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,classes={MyApplication.class})
@DataJpaTest
public class MyTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MyService myService;
    ....

    @Test
    public void myTest(){
    ....
    }
}

应用程序看起来像这样

@SpringBootApplication
@EnableJpaAuditing
@ComponentScan("de.myfirm.myservice.service")
public class  MyApplication{
....
}

在pom.xml中我有以下依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jersey</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

应用程序是一个使用Jersey的Web服务。启动应用程序时,嵌入式servlet容器按预期启动。在测试中,我得到了例外

java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
....
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.

2 个答案:

答案 0 :(得分:2)

我发现@SpringBootTest和@DataJpaTest无法协同工作,请看这个问题

https://github.com/spring-projects/spring-boot/issues/6345

答案 1 :(得分:1)

您要在pom.xml中排除spring-boot-starter-tomcat。 要使用嵌入式tomcat运行spring boot test,您将需要此依赖项。

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>1.4.2.RELEASE</version>
    <scope>test</scope>
</dependency>