【问题标题】:Context Configuration in spock testspock 测试中的上下文配置
【发布时间】:2015-08-30 17:59:22
【问题描述】:

我有这样的Application类:

@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")发现):

@RestController
@RequestMapping("/user")
public class UserService {

@Autowired
private UserRepository userRepository;

@RequestMapping(method = RequestMethod.POST)
public User createUser(@RequestParam String login, @RequestParam String password){
    return userRepository.save(new User(login,password));
} 

我尝试测试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 为 null - 未连接。表示未加载上下文。请告诉我测试的ContextConfiguration哪里出了问题。

【问题讨论】:

    标签: java spring spock applicationcontext


    【解决方案1】:

    已解决:

    @ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = Application.class)
    @WebAppConfiguration
    @IntegrationTest
    

    RestTemplate 的使用方法

    as in this question

    【讨论】:

      【解决方案2】:

      由于赏金需要一些详细说明,因此对此进行了扩展:默认情况下,Spring 在单元测试中不会连接 bean。这就是需要这些注释的原因。我会试着把它们分解一下:

      • 当没有定义特定的@ContextConfiguration(loader=...) 时,使用 SpringBootContextLoader 作为默认的 ContextLoader。
      • 在不使用嵌套@Configuration 且未指定显式类时自动搜索@SpringBootConfiguration。

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

      【讨论】:

      • 能否请您添加一些关于使用 Spring(不是 SpringBoot)的说明?
      • @ДмитрийКулешов 后两个注解并非特定于 Spring Boot。我认为第一个可以用“@RunWith”之类的东西代替,但我不确定,因为我只在 Spring Boot 中使用过这些。你具体想做什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      相关资源
      最近更新 更多