java 在Spock中自动连接的测试主题上获取NullPointerException

5lwkijsr  于 2023-02-20  发布在  Java
关注(0)|答案(2)|浏览(105)

我有一个简单的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(完整的代码是here)。事实上,当这个测试运行时,Spring上下文甚至没有出现,这是我在使用Spock和Sping Boot 的2年中从未见过的。我错过了什么?这似乎是一个非常简单的用例。

shyt4zoc

shyt4zoc1#

您需要将Spock更新到2.4-M1,因为它修复了Spring Boot 3/Spring 6的一个问题。
参见Spring Boot 3 with testing in Spock doesn't create context in @SpringBootTest test

esyap4oy

esyap4oy2#

我可以看到您的getBeerById方法没有使用@RequestMapping或类似方法Map到URL端点,我认为它应该是:

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

相关问题