Getting NullPointerException on autowired test subject in Spock
Asked Answered
P

2

1

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.

Pozzy answered 18/2, 2023 at 1:11 Comment(0)
B
2

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

See Spring Boot 3 with testing in Spock doesn't create context in @SpringBootTest test

Barna answered 19/2, 2023 at 1:39 Comment(1)
Awesome, that fixed it! I wish I'd noticed the "no Spring context" part earlier.Pozzy
L
0

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);
    }
Lull answered 18/2, 2023 at 3:36 Comment(1)
I have since added that annotation, but still the same result. But, since I'm calling the controller method directly (rather than using MockMvc), that shouldn't matter, right? And the larger problem is that the Spring Context is not coming up at all. I think if I fix that it'll fix the NPE.Pozzy

© 2022 - 2024 — McMap. All rights reserved.