虽然我在尝试时遵循了Spring Boot Guide:
<packageSources>
我只是得到一条消息,即没有注入WebApplicationContext。我有
@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())
}
}
在我的.pom中,正如指南建议的那样,但仍然没有成功。我错过了什么?我需要应用程序上下文,因此所有bean都被注入。有什么想法吗?
答案 0 :(得分:2)
您可以尝试将mockMvc构造移动到setup
方法吗?
def setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build()
}
答案 1 :(得分:0)
您还可以使用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())
}
}