使用DB的Spring Boot应用程序 - 使用@DirtiesContext重新创建上下文后,Test类失败

时间:2015-01-07 15:51:51

标签: java junit spring-boot spring-test

我正在尝试执行一组Spring Boot Application的JUnit4测试类,它包含多个Web服务并配置了数据库。

在每次测试后清除上下文很方便,所以我在每个测试类上都包含一个@DirtiesContext注释,因为这个注释的默认行为是在AFTER_CLASS中设置的。

我遇到的问题是第一个测试类运行良好,但后面的测试类总是失败。

所以我创建了2个简单的JUnit类来尝试解决这个问题。两者都是等于,测试方法是空的,所以总是应该返回成功:

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import urlshortener2014.goldenbrown.Application;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port=0")
@DirtiesContext
public class ApplicationTests {

    @Value("${local.server.port}")
    private int port = 0;

    @Test
    public void testAlwaysOk() throws Exception {

    }
}

我已经在eclipse中执行了两个测试类(ApplicationTests和SameApplicationTests),并通过“gradle test”,在这两种情况下,第二个和后面的测试类在上下文清理后都失败了。

我怀疑问题与应用程序的数据库有关,但是没有正确地重新创建,因为输出跟踪多次指向数据库相关的错误。但我不确定这是怎么发生或者为什么发生这种情况以及如何解决它。

这是一个带有“gradle test”输出的Gist(正常输出, - info输出和--debug输出): https://gist.github.com/jgbarcos/c8b34c5c292ca1fabc1d

以下是正在使用的build.gradle(仅测试2个简单类):

eclipse {
   project {
      name = "UrlShortener2014.goldenBrown"
   }
}

dependencies {
   compile project(":common")
     // Provides java script libraries for static content
   compile("org.webjars:bootstrap:3.0.3")
   compile("org.webjars:jquery:2.0.3-1")
   compile 'org.apache.httpcomponents:httpclient:4.3.6'
   compile 'nl.bitwalker:UserAgentUtils:1.2.4'
   compile 'org.springframework:spring-context'
   compile 'org.springframework:spring-context-support'
   compile 'net.sf.ehcache:ehcache:2.7.4'
   compile("org.springframework.boot:spring-boot-starter-web:1.2.0.RELEASE")
   compile 'org.springframework:spring-test:4.1.4.RELEASE'
   testCompile 'junit:junit:4.10'
}

// Used for @DirtiesContext problem
test{
    scanForTestClasses = false
    // This should get only "ApplicationTests.class" and "SameApplicationTests.class"
    include "**/*ApplicationTests.class"
}

这是我创建的GitHub分支,用于重现团队项目文件夹(goldenBrown)的问题: https://github.com/jgbarcos/UrlShortener2014/tree/debug_branch/goldenBrown

注意:项目取决于另一个名为common的项目在“/ common”而不是“/ goldenBrown”,这可能有点棘手)

希望这有助于理解这个问题,提前谢谢。

1 个答案:

答案 0 :(得分:2)

您的代码没问题。错误在schema-hsqldb.sql。只需在文件开头添加以下两行:

DROP TABLE CLICK IF EXISTS;
DROP TABLE SHORTURL IF EXISTS;

确保每次重新创建数据库时,都会删除现有表。

相关问题