1

我正在使用 Spring-Boot 建立一个演示项目。对于实体持久性,我使用基于接口的 Spring 生成的 Repository 实现:

@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:无法调用空对象上的方法 findByNameContaining()

不过,摆弄不同的注释并没有产生工作场景。有什么猜测吗?

4

1 回答 1

1

是的,我明白了:

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

于 2018-10-21T20:21:47.017 回答