我正在尝试执行Spring Boot应用程序的一组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中并通过“ gradle test”执行了两个测试类(ApplicationTests和SameApplicationTests),并且在两种情况下,第二个及以下测试类在清除上下文后均失败了。
我怀疑该问题与应用程序的数据库有关,未正确重新创建该数据库,因为输出跟踪多次指向与数据库相关的错误。但是我不确定这是怎么发生的或为什么发生的以及如何解决它。
这是具有“等级测试”输出(正常输出,-info输出和--debug输出)的Gist: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”而不是“ / goldenBrown”中称为common的另一个项目,这可能有点棘手)
希望这有助于理解问题,在此先感谢。
您的代码正常。故障出在schema-hsqldb.sql中。只需在文件开头添加以下两行:
DROP TABLE CLICK IF EXISTS;
DROP TABLE SHORTURL IF EXISTS;
这样可以确保每次重新创建数据库时,都会删除现有表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句