在 Spock 规范中注入时,WebApplicationContext 不会自动装配

WebApplicationContext does not Autowire when injecting in Spock Specification

虽然我遵循了 Spring 引导指南,但在尝试时:

@SpringApplicationConfiguration(classes=MainWebApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles("integration-test")

class FirstSpec extends Specification{
  @Autowired
  WebApplicationContext webApplicationContext

  @Shared
  MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build()

  def "Root returns 200 - OK"(){

      when:
      response = mockMvc.perform(get("/"))

      then:
      response.andExpect(status().isOk())
  }
}

我刚收到消息说 WebApplicationContext 未注入。我有

    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-spring</artifactId>
    </dependency>
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-maven</artifactId>
        <version>0.7-groovy-2.0</version>
    </dependency>

在我的 .pom 中,也正如指南所建议的那样,但仍然没有成功。我有什么想念的吗?我需要应用程序上下文,以便注入所有 bean。有什么想法吗?

您可以尝试将 mockMvc 构造移动到 setup 方法吗?

def setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build()
}

您还可以使用 Spock 1.2 中提供的 SpringBean 注释:https://objectpartners.com/2018/06/14/spock-1-2-annotations-for-spring-integration-testing/

这样做会更容易:

@SpringApplicationConfiguration(classes=MainWebApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
@WebMvcTest
@AutoConfigureMockMvc
@WebAppConfiguration
@ActiveProfiles("integration-test")

class FirstSpec extends Specification{
  @Autowired
  WebApplicationContext webApplicationContext

  @Autowired
  MockMvc mockMvc

  // if any service to mock
  @SpringBean
  MyService myService

  def "Root returns 200 - OK"(){

      when:
      response = mockMvc.perform(get("/"))

      then:
      response.andExpect(status().isOk())
  }
}

如果你不想模拟你的服务,你可以直接使用@SpringBootTest,它只用一个注解就可以完成同样的工作

@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("integration-test")

class FirstSpec extends Specification{
  @Autowired
  WebApplicationContext webApplicationContext

  @Autowired
  MockMvc mockMvc

  // if any service to mock
  @SpringBean
  MyService myService

  def "Root returns 200 - OK"(){

      when:
      response = mockMvc.perform(get("/"))

      then:
      response.andExpect(status().isOk())
  }
}