英文:
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-core
和spock-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.
答案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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论