【问题标题】:Spring-Boot and Spock fail when using Unroll使用 Unroll 时 Spring-Boot 和 Spock 失败
【发布时间】: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


【解决方案1】:

是的,我知道了:

RunWith 是罪魁祸首。在我的 Edit1 中,我注意到删除 @Test 的区别。这让我想到我可能将 JUnit 测试与 Spock 测试混淆了。此外,No runnable methods 让我思考。并且省略 @RunWith,因为它在其他 Spock 和 Spring 示例中几乎不存在,这似乎是个好主意。并且将 Spring bean 与@ContextConfiguration 连接起来非常好;-)。显然,@SpringBootTest 没有这样做?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2017-12-31
    • 2017-06-28
    • 2014-08-15
    • 2020-11-10
    • 2017-05-25
    • 2018-10-09
    相关资源
    最近更新 更多