spock 测试中的上下文配置

Context Configuration in spock test

我有这样的 Application class:

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

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
}

我也有UserServiceclass(被@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 为空 - 未连接。意味着未加载上下文。请告诉我测试的ContextConfiguration中的问题所在。

解决者:

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

RestTemplate 的用法

as in this question

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

  • Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=...) is defined.
  • Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.

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