【发布时间】:2019-10-06 10:57:09
【问题描述】:
我在网上似乎没有一种特定的标准方法可以使@DataJpaTest 正确运行。
@DataJpaTest 现在没有被使用,并且所有测试都使用@SpringBootTest 在服务或控制器级别运行,这是真的吗?
@Repository
public interface MyBeanRepository extends JpaRepository<MyBean, Long> {
}
@Configuration
@EnableJpaRepositories("com.app.repository.*")
@ComponentScan(basePackages = { "com.app.repository.*" })
public class ConfigurationRepository {
}
@Entity
public class MyBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Version
@Column(name = "version")
private Integer version;
@NotNull
@Size(min = 2)
private String name;
}
@DataJpaTest
public class MyBeanIntegrationTest {
@Autowired
MyBeanRepository myBeanRepository;
@Test
public void testMarkerMethod() {
}
@Test
public void testCount() {
Assertions.assertNotNull(myBeanRepository , "Data on demand for 'MyBean' failed to initialize correctly");
}
}
使用 Eclipse 运行->Run Junit 会显示这些日志。
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:73)
使用gradle test运行显示init失败的错误。
FAILURE: Build failed with an exception.
* What went wrong:
Test failed.
Failed tests:
Test com.app.repository.MyBeanIntegrationTest#initializationError (Task: :test)
这是 gradle 脚本。
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin")
}
}
plugins {
id 'org.springframework.boot' version '2.1.5.RELEASE'
id 'java'
id 'eclipse'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.app'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenLocal()
jcenter()
mavenCentral()
}
test {
useJUnitPlatform()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
runtimeOnly 'org.hsqldb:hsqldb'
testImplementation ('org.springframework.boot:spring-boot-starter-test') {
// exlcuding junit 4
exclude group: 'junit', module: 'junit'
}
/**
Test Dependencies Follows
**/
// junit 5 api
testCompile "org.junit.jupiter:junit-jupiter-api:5.2.0"
// For junit5 parameterised test support
testCompile "org.junit.jupiter:junit-jupiter-params:5.2.0"
// junit 5 implementation
testRuntime "org.junit.jupiter:junit-jupiter-engine:5.2.0"
// Only required to run junit5 test from IDE
testRuntime "org.junit.platform:junit-platform-launcher"
}
编辑:
这已在同一个存储库中解决并提交。 https://github.com/john77eipe/spring-demo-1-test
【问题讨论】:
-
如果您尊重标准包布局 (docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…),一切都应该正常。
-
@JBNizet 我找不到问题所在。
-
您在 com.app 包中没有任何使用
@SpringBootApplication注释的主应用程序类。 -
存储库项目不会包含
@SpringBootApplication对吗?或者我们应该为此放一个。另外,如果这不是一个 Spring Boot 项目,而是一个 Spring 项目,有没有办法让它仅用于测试?
标签: spring-boot gradle spring-data-jpa junit5