Java spock测试中的上下文配置

Java spock测试中的上下文配置,java,spring,spock,applicationcontext,Java,Spring,Spock,Applicationcontext,我有这样的应用程序类: @Configuration @EnableAutoConfiguration @ComponentScan @ImportResource("classpath:applicationContext.xml") @EnableJpaRepositories("ibd.jpa") public class Application { public static void main(String[] args) { SpringApplication.run(Ap

我有这样的
应用程序
类:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@ImportResource("classpath:applicationContext.xml")
@EnableJpaRepositories("ibd.jpa")
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
}
我还有
UserService
类(由
@EnableJpaRepositories(“ibd.jpa”)
发现):

我尝试测试
UserService

@ContextConfiguration
class UserServiceTest extends Specification {

@Autowired
def UserService userService


def "if User not exists 404 status in response sent and corresponding message shown"() {
    when: 'rest account url is hit'
    MockMvc mockMvc = standaloneSetup(userService).build()
        def response = mockMvc.perform(get('/user?login=wrongusername&password=wrongPassword')).andReturn().response
    then:
        response.status == NOT_FOUND.value()
        response.errorMessage == "Login or password is not correct"

}
但问题是: 测试中的UserService为空-未连接。表示未加载上下文。请告诉我测试的ContextConfiguration中的问题是在哪里解决的。

@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = Application.class)
@WebAppConfiguration
@IntegrationTest
rest模板的定义和使用


由于赏金需要一些细化,所以在此基础上进行扩展:Spring在单元测试中默认不会连接bean。这就是为什么需要这些注释。我会试着把它们分解一下:

  • (现在已弃用,取而代之)来自文档:
  • 当未定义特定的@ContextConfiguration(loader=…)时,使用SpringBootContextLoader作为默认的ContextLoader
  • 当未使用嵌套@Configuration且未指定显式类时,自动搜索@SpringBootConfiguration
  • 添加应用程序上下文,并且必须与
  • 实际确定如何加载“类级别”元数据

没有这些注释,Spring就不会连接测试配置所需的bean。这部分是出于性能原因(大多数测试不需要配置上下文)

能否请您添加一些关于使用Spring(非SpringBoot)的注释?@Бцццццццццццццц。我认为第一个可以用“@RunWith”之类的东西来代替,但我不确定,因为我只在Spring Boot中使用过这些。你具体想做什么?
@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = Application.class)
@WebAppConfiguration
@IntegrationTest