Context configuration in spock test
I have an application class like this:
@Configuration
@EnableAutoConfiguration
@ComponentScan
@ImportResource("classpath:applicationContext.xml")
@EnableJpaRepositories("ibd.jpa")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also I have a UserService class (discovered with @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));
}
********
And I am trying to check 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"
}
But the problem is this: UserService in the test is null - not connected. Means that the Context is not loaded. Please tell me where the problem is in the ContextConfiguration of the test.
+3
source to share
2 answers
Extending on this, as the bounty required some development: Spring does not hook into beans by default in unit tests. This is why these annotations are needed. I'll try to break them down a bit:
- @IntegrationTest (which is now deprecated in favor of @SpringBootTest ) from the docs:
- Uses SpringBootContextLoader as the default ContextLoader unless a specific @ContextConfiguration (loader = ...) is defined.
- Automatically looks for @SpringBootConfiguration when nested @Configuration is not used and no explicit classes are specified.
- @WebAppConfiguration adds application context and should be used with ...
- @ContextConfiguration actually defines how to load class-level metadata.
Without these annotations, Spring does not wire the beans required for your test configuration. This is partly for performance reasons (most tests do not require context tuning).
+1
source to share