gpt4 book ai didi

java - 如何配置Spock测试来加载Spring Context(对于@Autowired)?

转载 作者:行者123 更新时间:2023-12-02 02:46:19 25 4
gpt4 key购买 nike

我有这样的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 - 它没有成功@Autowired;这表明 Spring 上下文没有加载。如何配置才能成功 Autowiring ?

最佳答案

解决方法:

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

RestTemplate 和使用

as in this question

关于java - 如何配置Spock测试来加载Spring Context(对于@Autowired)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30841795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com