在Spock中@Autowired测试主题时出现空指针异常。

huangapple go评论72阅读模式
英文:

Getting NullPointerException on autowired test subject in Spock

问题

我有一个简单的Spock规范,使用@SpringBootTest进行注释,被测试的类使用@Autowired进行注释,但在单元测试中测试主题为空。控制器使用@Controller注解。以下是测试代码:

@SpringBootTest
class BeerControllerTest extends Specification {
    @Autowired
    BeerController testSubject

    def "get beer by ID"() {
        when:
        def result = testSubject.getBeerById(UUID.randomUUID())

        then:
        result
        println result
    }
}

我在类路径中包括了spock-corespock-spring(完整代码在这里)。实际上,当运行此测试时,Spring上下文甚至没有启动,这在我使用Spock和Spring Boot约2年的时间里从未见过。我在这里漏掉了什么?这似乎是一个非常简单的用例。

英文:

I have a simple Spock specification annotated with @SpringBootTest and the class under test annotated with @Autowired, but the test subject is null in the unit test. The controller is annotated with the @Controller stereotype. Here's the test:

@SpringBootTest
class BeerControllerTest extends Specification {
    @Autowired
    BeerController testSubject

    def "get beer by ID"() {
        when:
        def result = testSubject.getBeerById(UUID.randomUUID())

        then:
        result
        println result
    }
}

I have spock-core and spock-spring on the classpath (full code is here). In fact, the Spring Context is not even coming up when this test is run, which I have never seen in ~2 years of using Spock and Spring Boot. What am I missing here? It seems like a pretty simple use-case.

答案1

得分: 2

你需要升级到 Spock 版本 2.4-M1,因为它修复了与 Spring Boot 3 / Spring 6 相关的问题。

查看 https://stackoverflow.com/q/74633439/2145769

英文:

You need to update to Spock to 2.4-M1 as it fixes a problem with Spring Boot 3 / Spring 6.

See https://stackoverflow.com/q/74633439/2145769

答案2

得分: 0

我看到你的getBeerById方法没有使用@RequestMapping或类似的方式映射到URL端点,我认为应该这样做:

@RequestMapping("/api/v1/beer/{id}")
public Beer getBeerById(@PathVariable UUID id) {
    return beerService.getBeerById(id);
}
英文:

I can see that your getBeerById method not mapped to a URL endpoint using @RequestMapping or similar, I think that it should be:

    @RequestMapping("/api/v1/beer/{id}")
    public Beer getBeerById(@PathVariable UUID id) {
        return beerService.getBeerById(id);
    }

huangapple
  • 本文由 发表于 2023年2月18日 09:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定