I have created simple Rest Api service using spring boot 2.2.5.RELEASE, I have just enabled Spring Security in the application. The JUnits are not working. I tried some of the ways to solve this issue but its not working.
Looking at references in books and online (including questions answered in Stack Overflow) I learned about two methods to disable security in tests:
- @WebMvcTest(value =MyController.class, secure=false)
- @AutoConfigureMockMvc(secure = false)
- @EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
All these annotation i tried one by one on Test class but its not working.
1.@WebMvcTest(value =MyController.class, secure=false)
2.@AutoConfigureMockMvc(secure = false)
Both of these settings were identified in various Stack Overflow answers as being deprecated, but I tried them anyway.
Unfortunately, they didn't work. Apparently, in Version 2.2.1 of Spring Boot (the version I am using) secure isn't just deprecated, it is gone. Tests with the annotations using the "secure = false" parameter do not compile. The code snippet looks like this:
Code Snippet
package com.akarsh.controller;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
@SpringBootTest(classes = SpringBootProj2Application.class,webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SurveyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private SurveyService surveyService;
@Test
public void retrieveDetailsForQuestion_Test() throws Exception {
Question mockQuestion = new Question("Question1",
"Largest Country in the World", "Russia", Arrays.asList(
"India", "Russia", "United States", "China"));
Mockito.when(
surveyService.retrieveQuestion(Mockito.anyString(), Mockito
.anyString())).thenReturn(mockQuestion);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/surveys/Survey1/questions/Question1").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = "{\"id\":\"Question1\",\"description\":\"Largest Country in the World\",\"correctAnswer\":\"Russia\",\"options\":[\"India\",\"Russia\",\"United States\",\"China\"]}";
String actual=result.getResponse().getContentAsString();
JSONAssert.assertEquals(expected,actual , false);
}
\\
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// Authentication : User-->Roles
// Authorization : Role->Access
@Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}secret").roles("USER")
.and()
.withUser("akarsh").password("{noop}ankit").roles("ADMIN","USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and().authorizeRequests()
.antMatchers("/surveys/**").hasRole("USER")
.antMatchers("/users/**").hasRole("USER")
.antMatchers("/**").hasRole("ADMIN")
.and().csrf().disable()
.headers().frameOptions().disable();
}
}
\ Getting following exception
Description:
A component required a bean of type 'org.springframework.security.config.annotation.ObjectPostProcessor' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.config.annotation.ObjectPostProcessor' in your configuration.
2020-04-13 14:51:15.659 ERROR 5128 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@36902638] to prepare test instance [com.akarsh.controller.SurveyControllerTest@3eb8057c]
\\
@RestController
public class SurveyController {
@Autowired
SurveyService surveyService;
@GetMapping("/surveys/{surveyId}/questions")
public List<Question> retrieveQuestionForSrvey(@PathVariable String surveyId)
{
if(surveyId!=null)
{
return surveyService.retrieveQuestions(surveyId);
}
return null;
}
@GetMapping("/surveys/{surveyId}/questions/{questionId}")
public Question retrieveQuestion(@PathVariable String surveyId,@PathVariable String questionId)
{
if(surveyId!=null)
{
return surveyService.retrieveQuestion(surveyId, questionId);
}
return null;
}
@PostMapping("/surveys/{surveyId}/questions")
public ResponseEntity<?> addQuestionForSrvey(@PathVariable String surveyId, @RequestBody Question question) {
Question createdTodo = surveyService.addQuestion(surveyId, question);
if (createdTodo == null) {
return ResponseEntity.noContent().build();
}
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(createdTodo.getId()).toUri();
return ResponseEntity.created(location).build();
}