【发布时间】:2018-10-19 13:58:39
【问题描述】:
我正在使用 Spring-Boot 设置一个演示项目。对于实体持久性,我使用 Spring 生成的基于接口的存储库实现:
@Repository
public interface MovieRepository extends JpaRepository<Movie, Long> {
List<Movie> findByNameContaining(String name);
List<Movie> findByRelease(LocalDate release);
List<Movie> findByReleaseBetween(LocalDate start, LocalDate end);
List<Movie> findByNameContainingAndRelease(String name, LocalDate release);
}
为了测试这一点,我将 Spock 与 Groovy 一起使用,效果非常好:
@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest
class MovieRepositoryTest extends Specification {
@Autowired
MovieRepository movieRepository
@Test
def findByNameContaining_shouldFindCorrectMovies() {
given:
movieRepository = this.movieRepository
when:
def result = movieRepository.findByNameContaining("Iron Man")
then:
result.size() == 3
}
}
但当我尝试混入 Spock 的 @Unroll 时,一切都崩溃了:
@Test
@Unroll
def findByNameContaining_shouldFindCorrectMovies() {
given:
movieRepository = this.movieRepository
when:
def result = movieRepository.findByNameContaining(query)
then:
result.size() == expected
where:
query || expected
"Iron Man" || 3
"Hulk" || 1
"Thor" || 3
"Avengers" || 3
"Thanos" || 0
"" || 20
}
结果:
[INFO] Running com.spring.boot.demo.repositories.MovieRepositoryTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 s <<< FAILURE! - in com.spring.boot.demo.repositories.MovieRepositoryTest
[ERROR] initializationError(com.spring.boot.demo.repositories.MovieRepositoryTest) Time elapsed: 0.003 s <<< ERROR!
java.lang.Exception: Method $spock_feature_0_0 should have no parameters
我不知道可能导致这种情况的原因。 欢迎任何帮助。 谢谢
编辑 1: 嗯,这很有趣。我尝试了以下方法: * 移除 @Test -> java.lang.Exception: 没有可运行的方法 * 删除 @RunWith 和 @ContextConfiguration -> Unroll 有效,但未注入/连接 movieRepository:java.lang.NullPointerException: 无法在 null 对象上调用方法 findByNameContaining()
虽然摆弄不同的注释并没有产生工作场景。有什么猜测吗?
【问题讨论】:
-
您确定需要将@Test 放在方法之上吗?我以为 Spock 不需要那个 jUnit 注释...
-
我同意@HansWesterbee,你不需要使用
@Test。不确定这是否是错误的原因。@RunWith(SpringRunner.class)和@ContextConfiguration很可能也已过时。@SpringBootTest注释应该足以启动上下文。请删除它们,然后重试。如果它没有帮助您使用的是什么 Spring Boot 和 Spock 版本? -
我提到它是因为注释可能会混淆 Spock 所做的 Groovy 魔法。
-
这值得一试。将尽快做到这一点。 Tnx
标签: spring spring-boot spock unroll