RestAssuredMockMvc - getting 404 - java

I'm trying to migrate to RestAssuredMockMvc from regular MockMvc for a Spring Web Application, but I ran into a problem:
When trying to test against a simple resource, I get a 404. I wrote an equivalent MockMvc test as well, which succeeds.
Here are the two tests:
RestAssured:
package at.mycompany.iad.remote.internalorg.v1.controller;
import at.mycompany.iad.remote.internalorg.v1.resource.OrgProfileResource;
import at.mycompany.iad.remote.internalorg.v1.testconfig.TestConfig;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import static io.restassured.RestAssured.when;
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestConfig.class)
public class OrgProfileControllerITRestAssured {
#Autowired
private WebApplicationContext context;
#Before
public void initRestAssured() {
RestAssuredMockMvc.webAppContextSetup(context);
// RestAssuredMockMvc.standaloneSetup(new OrgProfileResource(null)); //I tried this too, same result
}
#Test
public void getAd() throws Exception {
when()
.get("/examplepartnerid/profile")
.then()
.statusCode(HttpStatus.OK.value());
}
}
And MockMvc:
package at.mycompany.iad.remote.internalorg.v1.controller;
import at.mycompany.iad.remote.internalorg.v1.testconfig.TestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestConfig.class)
public class OrgProfileControllerITMockMvc {
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
#Test
public void testGet() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(
get("/examplepartnerid/profile"))
.andExpect(status().is(200)).andReturn();
}
}
And the controller being tested:
package at.mycompany.iad.remote.internalorg.v1.resource;
import at.mycompany.iad.remote.internalorg.v1.controller.OrgProfileController;
import at.mycompany.iad.remote.internalorg.v1.dto.OrgProfileDto;
import io.swagger.annotations.*;
import no.finntech.kernel.framework.exception.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
#RestController
#RequestMapping(value = "/{partnerId}/profile")
#Api(description = "Operations used for updating organisation services")
public class OrgProfileResource {
private final OrgProfileController controller;
#Autowired
public OrgProfileResource(OrgProfileController controller) {
this.controller = controller;
}
#RequestMapping(method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
#ApiOperation(value = "get organisation profile")
#ApiResponses({
#ApiResponse(code = 200, message = "returns organisation profile for supplied partnerId"),
#ApiResponse(code = 404, message = "no organisation found with supplied partnerId")
})
public ResponseEntity<OrgProfileDto> getOrgProfile(
#ApiParam(required = true) #PathVariable String partnerId
) throws SystemException {
OrgProfileDto orgProfile = controller.getOrgProfile(partnerId);
return ResponseEntity.status(HttpStatus.OK).body(orgProfile);
}
#RequestMapping(method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.ACCEPTED)
#ApiOperation(value = "get organisation services")
#ApiResponses({
#ApiResponse(code = 204, message = "saved organisation services for supplied partnerId"),
#ApiResponse(code = 404, message = "no organisation found with supplied partnerId")
})
public void postOrgProfileServices(
#ApiParam(required = true) #PathVariable String partnerId,
#RequestBody OrgProfileDto requestDto
) throws SystemException {
controller.saveOrgProfile(partnerId, requestDto);
}
#RequestMapping(value = "/image", method = RequestMethod.POST, headers = "content-type=multipart/form-data", consumes = "multipart/form-data")
#ApiOperation(value = "Sets an image to existing organisation")
#ApiResponses({
#ApiResponse(code = 201, message = "The reference to the image within mycompany IAd system"),
#ApiResponse(code = 404, message = "no organisation found for given org-name")
})
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity addImageToProfile(
#ApiParam(required = true) #PathVariable String partnerId,
HttpServletRequest request) throws IOException, SystemException {
controller.saveImage(partnerId, request);
return ResponseEntity.status(202).build();
}
}

Related

I am unable to successfully test my controller

I am getting the following error when trying to test my controller. I know the error is being thrown by something in the security configuration, just not sure what it is exactly. org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'springSecurityFilterChain' is expected to be of type 'javax.servlet.Filter' but was actually of type 'org.springframework.beans.factory.support.NullBean'.
This is the test class
package com.chama.chamaservice.user;
import com.chama.chamaservice.auth.CustomAuthenticationFilter;
import com.chama.chamaservice.auth.CustomAuthorizationFilter;
import com.chama.chamaservice.config.SecurityConfig;
import org.junit.Before;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#ExtendWith(SpringExtension.class)
#WebMvcTest(controllers = UserController.class)
class UserControllerTest {
#MockBean
private WebSecurityConfiguration webSecurityConfiguration;
#MockBean
private UserService userService;
#MockBean
private UserDetailsService userDetailsService;
#MockBean
private SecurityConfig securityConfig;
#MockBean
private WebApplicationContext context;
#MockBean
private CustomAuthorizationFilter customAuthorizationFilter;
#Autowired
private MockMvc mockMvc;
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
#Test
#WithMockUser(username = "254704760842", roles = {"PLATFORM_SUPER_ADMIN"})
#DisplayName("Should list all users GET: /api/users/")
void shouldGetUsers() throws Exception {
mockMvc.perform(get("/api/users"))
.andExpect(status().is(200))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE));
}
}
Note that the test runner actually reaches the test class and the error is thrown at this line mockMvc.perform(get("/api/users"))
This is the controller under test
#GetMapping("")
#JsonView(Views.Public.class)
#PreAuthorize("hasAuthority('CAN_VIEW_ALL_PLATFORM_MEMBERS')")
public ResponseEntity<List<User>> getUsers() {
return ResponseEntity.ok().body(userService.getUsers());
}
This is my custom authorisation filter class.
package com.chama.chamaservice.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chama.chamaservice.config.ApplicationUserRole;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
#Slf4j
public class CustomAuthorizationFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (request.getServletPath().equals("/api/login") || request.getServletPath().equals("/api/refresh/token")) {
filterChain.doFilter(request, response);
} else {
// Generate new access token from refresh token
String authorizationHeader = request.getHeader(AUTHORIZATION);
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
try {
String token = authorizationHeader.substring("Bearer ".length());
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = verifier.verify(token);
String phoneNumber = decodedJWT.getSubject();
String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
Collection<SimpleGrantedAuthority> authorities = Arrays.stream(roles)
.map(ApplicationUserRole::valueOf) // <- parsing every String to ApplicationUserRole
.map(ApplicationUserRole::getGrantedAuthorities) // <- converting every ApplicationUserRole to a set of GrantedAuthority
.flatMap(Collection::stream) // <- converting stream of sets to a stream of GrantedAuthority
.collect(Collectors.toList());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phoneNumber, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);
} catch (Exception e) {
log.error("Error logging in: {}", e.getMessage());
response.setHeader("error", e.getMessage());
response.setStatus(FORBIDDEN.value());
Map<String, String> error = new HashMap<>();
error.put("message", e.getMessage());
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), error);
}
} else {
filterChain.doFilter(request, response);
}
}
}
}
And finally, this is my security config class
package com.chama.chamaservice.config;
import com.chama.chamaservice.auth.CustomAuthenticationFilter;
import com.chama.chamaservice.auth.CustomAuthorizationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
#EnableWebSecurity
#RequiredArgsConstructor
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
/*
* Setting custom login endpoint
* */
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean());
customAuthenticationFilter.setFilterProcessesUrl("/api/login");
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/api/login/**", "/api/token/refresh/**").permitAll()
.antMatchers("/api/users/save/**").permitAll()
.antMatchers("/api/daraja/register-url/validation/**").permitAll()
.antMatchers("/api/daraja/register-url/confirmation/**").permitAll()
.anyRequest()
.authenticated()
.and();
http.addFilter(customAuthenticationFilter);
http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManager();
}
}

Spring Boot Integration Testing - TestRestTemplate null

I am using Spring Boot 2.1.2 and junit-jupiter-api-5.3.2 and I am doing integration testing.
My test case is this:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ril.vms.hawkeye.otp.dto.SendOTPRequestDTO;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
#SpringBootTest(classes = MyApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
#ActiveProfiles("sit")
public class OtpControllerIntegrationTest
{
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate;
#Test
public void sendOtpTest() throws Exception {
SendOTPRequest otpRequest = new SendOTPRequestDTO();
otpRequest.setClientId("default2");
otpRequest.setTag("tag");
otpRequest.setMobileNumber("9999999999");
ResponseEntity<String> responseEntity = this.restTemplate
.postForEntity("http://localhost:" + port + "/sendOtp", otpRequest, String.class);
assertEquals(201, responseEntity.getStatusCodeValue());
}
}
But I am getting java.lang.NullPointerException at below line.
ResponseEntity<String> responseEntity = this.restTemplate ...
try this template
public ArrayList<ABC> lovApi(LovsRequestDto reqObj) {
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity<ABCDto> entity = new HttpEntity<ABCDto>(reqObj, headers);
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
String postUrl = "http://80.111.23.23.33333.....";
ResponseEntity<LovsResponse> postResponse = restTemplate.exchange(postUrl, HttpMethod.POST, entity, LovsResponse.class);
return postResponse.getBody().getLovs_response_details().getLovList();
}
try to create a new restTemplate bean in sendOtpTest mehtods. you get null point because this.restTemplate is not be instation; wish help you;

No mapping for GET /me

I have this spring boot app and I'm new to spring boot. I have this controller created but it throws 404 and says No mapping for GET /me in the console. I couldn’t find the issue and I need to get this as soon as possible.
Here's the log: https://pastebin.com/Qf5W6MZU
Any other endpoints in this controller also doesn’t work.
import org.sefglobal.scholarx.exception.BadRequestException;
import org.sefglobal.scholarx.exception.NoContentException;
import org.sefglobal.scholarx.exception.ResourceNotFoundException;
import org.sefglobal.scholarx.exception.UnauthorizedException;
import org.sefglobal.scholarx.model.Mentee;
import org.sefglobal.scholarx.model.Profile;
import org.sefglobal.scholarx.model.Program;
import org.sefglobal.scholarx.service.IntrospectionService;
import org.sefglobal.scholarx.util.EnrolmentState;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/me")
public class AuthUserController {
private final IntrospectionService introspectionService;
public AuthUserController(IntrospectionService introspectionService) {
this.introspectionService = introspectionService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public Profile getLoggedInUser(#CookieValue(value = "profileId", defaultValue = "-1") long profileId)
throws ResourceNotFoundException, UnauthorizedException {
return introspectionService.getLoggedInUser(profileId);
}
#GetMapping("/programs/mentee")
#ResponseStatus(HttpStatus.OK)
public List<Program> getMenteeingPrograms(#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, NoContentException {
return introspectionService.getMenteeingPrograms(profileId);
}
#PutMapping("/mentor/{id}/confirmation")
#ResponseStatus(HttpStatus.OK)
public Mentee confirmMentor(#PathVariable long id,
#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, BadRequestException {
return introspectionService.confirmMentor(id, profileId);
}
}
I found the issue I haven’t included the package.

SpringBoot Rest Controller Integration test always gives 401 unauthorized

I have a rest controller, which has simple CRUD operations. I am trying to write integration test.
Below is my RestController:
package com.gasx.corex.scheduler.controller;
import java.awt.*;
import java.util.List;
import com.gasx.corex.scheduler.service.SchedulerJobServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.service.SchedulerJobService;
#RestController
#RequestMapping("/gasx/restscd")
public class SchedulerJobController {
#Autowired
private SchedulerJobServiceI schedulerJobService;
#RequestMapping(method = RequestMethod.GET , path="/getschedulerjobs" , produces= MediaType.APPLICATION_JSON_VALUE)
public List<SchedulerJob> getAllSchedulerJobs() {
return schedulerJobService.getAllSchedulerJobs();
}
#RequestMapping(method = RequestMethod.POST, value = "/addschedulerjob")
public void addSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.addSchedulerJob(schedulerJob);
}
#RequestMapping(method = RequestMethod.POST, value = "/updateschedulerjob")
public void updateSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.updateSchedulerJob(schedulerJob);
}
#RequestMapping(method = RequestMethod.POST, value = "/deleteschedulerjob")
public void deleteSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.deleteSchedulerJob(schedulerJob);
}
}
I have written Integration test for all of the endpoints in RestController
Integration test class :-
package com.gasx.corex.ext.scheduler.integrationtest.domain;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gasx.corex.base.configuration.CoreConfiguration;
import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.ext.scheduler.domain.utils.SchedulerJobType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import sun.security.krb5.internal.Ticket;
import org.springframework.http.HttpMethod;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.io.IOException;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT , properties = {
"management.server.port=0", "management.context-path=/admin" ,"security.basic.enabled=false"} )
#EnableAutoConfiguration
#ContextConfiguration( classes = {CoreConfiguration.class } )
#AutoConfigureMockMvc
public class SchedulerJobTestInt {
#LocalServerPort
private int port ;
#Autowired
private TestRestTemplate testRestTemplate;
#Autowired
WebApplicationContext context;
#Autowired
private MockMvc mockMvc;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
#Test
public void getAllSchedulerJobsIntTest() throws Exception {
ResponseEntity<String> response = testRestTemplate.getForEntity("http://localhost:" + port +"/gasx/restscd/getschedulerjobs", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(response.getBody());
assertThat(responseJson.isMissingNode()).isFalse();
assertThat(responseJson.toString()).isEqualTo("[]");
}
#Test
public void addSchedulerJobIntTest() throws Exception{
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
String plainCredentials="gasx:gasx!";
String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials);
headers.add("Accept" , "application/json");
HttpEntity<String> entity = new HttpEntity<String>(asJsonString(schedulerJob), headers);
// ResponseEntity<Void> response = testRestTemplate.postForEntity("http://localhost:"+port +"/gasx/restscd/addschedulerjob", entity,Void.class);
ResponseEntity<Void> response = testRestTemplate.postForEntity("http://localhost:" + port +"/gasx/restscd/addschedulerjob", asJsonString(schedulerJob),Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
#Test
public void updateSchedulerJobTest(){
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
ResponseEntity<Void> response = testRestTemplate.withBasicAuth("gasx" ,"gasx!").postForEntity("http://localhost:" + port +"/gasx/restscd/updateschedulerjob", schedulerJob,Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
#Test
public void deleteSchedulerJob(){
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
ResponseEntity<Void> response = testRestTemplate.withBasicAuth("gasx" ,"gasx!").postForEntity("http://localhost:" + port +"/gasx/restscd/deleteschedulerjob", schedulerJob,Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
My problems:
1.)Wheneever I put breakpoint in Rest Controller, it doesnt' stop there, actually it is not getting invoked.
2.)When I run the test for GET it returns sign-in html page from response.getBody()
3.)When I run the test for POST it returns status 401 unauthorized
tried numerious possible solutions on google
even disabled spring security by commenting the the configuration still it doesn't work.
I can call the same Rest Controller from my Unit test and can stop the breakpoints.
My security configurations:-
package com.gasx.corex.scheduler.server;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import com.gasx.corex.ext.user.domain.DefaultRoles;
#Configuration
#EnableWebSecurity
#Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// #formatter:off
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.httpBasic().and()
.authorizeRequests()
.antMatchers("/gasx/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
.antMatchers("/webjars/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
.antMatchers("/monitor/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ACTUATOR.getName())
// dev urls
.antMatchers("/h2-console/**").hasAuthority(DefaultRoles.ROOT.getName())
.antMatchers("/swagger*/**","/v2/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName())
.anyRequest().denyAll();
// #formatter:on
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
Tried one more thing, added below class to my package :-
package com.gasx.corex.ext.scheduler.integrationtest.domain;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class AllowAnonymousWebAccess extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity web) throws Exception {
web.antMatcher("**/*").anonymous();
}
}
and now it gives 404.
I don't know anything about this project's SecurityConfiguration (you should provide some more information about it), but I think that you should provide some authorization data (Like a JWT in the Authorization header, or so)
Could you give me some more information about the SecurityConfig? (look for org.springframework.security.config.something.something... imports )
EDIT
I took a look at your code, and actually this part
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.httpBasic().and()
.authorizeRequests()
.antMatchers("/gasx/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
is protecting your API with an httpBasic type authorization. You shold provide the credentials in the header to test your application.

JUnit test is not triggering method in Spring controller

I want to test my controller with the help of JUnit. I am new to this. I have written some code for this but it is not coming to my function listCard. My controller is:
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/v1/card")
#Configuration
public class CardManagementController {
private final static Logger LOG = LoggerFactory
.getLogger(CardManagementController.class);
#Autowired
ICardService cardService;
#RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.GET)
public #ResponseBody GetCardResponse getCard(
#ModelAttribute #Valid GetCardRequest request, BindingResult results)
throws RuntimeException, ValidationException {
if (results.hasErrors()) {
LOG.error("error occured occur while fetching card response");
throw new ValidationException(
"Error Occoured while validiating card request");
}
GetCardResponse response = null;
response = cardService.getCard(request);
return response;
}
#RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.POST)
public #ResponseBody AddCardResponse addCard(
#ModelAttribute AddCardRequest request, BindingResult results)
throws RuntimeException, ValidationException {
if (results.hasErrors()) {
LOG.error("error occured while adding the card");
throw new ValidationException(
"Error Occoured while validiating addcard request");
}
LOG.debug("add Card with POST method");
AddCardResponse response = null;
response = cardService.addCard(request);
return response;
}
#RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.DELETE)
public #ResponseBody DeleteCardResponse deleteCard(
#ModelAttribute #Valid DeleteCardRequest request,
BindingResult results) throws RuntimeException, ValidationException {
if (results.hasErrors()) {
LOG.debug("error occured while delting the card");
throw new ValidationException(
"Error Occoured while validiating delete card request");
}
DeleteCardResponse response = null;
response = cardService.deleteCard(request);
return response;
}
#RequestMapping(value = RestURIConstants.LISTCARD, produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.GET)
public #ResponseBody ListCardResponse listCard(
#ModelAttribute #Valid ListCardRequest request) throws RuntimeException, ValidationException {
ListCardResponse response = null;
response = cardService.listCards(request);
return response;
}
#ExceptionHandler({ ValidationException.class})
#ResponseBody
public CPPException handleValidationException(ValidationException ex) {
LOG.error("Exception occoured",ex);
CPPException exception = new CPPException(ex.getMessage());
exception.setStatus(500);
return exception;
}
#ExceptionHandler({RuntimeException.class})
#ResponseBody
public CPPException handleException(RuntimeException ex) {
LOG.error("Exception occoured", ex);
CPPException exception = new CPPException("Internal Server Error");
exception.setStatus(500);
return exception;
}
}
and I have written the following code for testing:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.my.cpp.controller.CardManagementController;
import com.my.cpp.request.ListCardRequest;
import com.my.cpp.service.impl.CardServiceImpl;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:/spring/application-context.xml"})
public class CardApiTest {
private MockMvc mockMvc;
//#Autowired
private CardManagementController cm=new CardManagementController();
#Autowired
private CardServiceImpl cmr;
#Before
public void setUp() throws Exception {
mockMvc= MockMvcBuilders.standaloneSetup(cm).build();
}
#Test
public void testList() throws Exception{
final ListCardRequest lr=new ListCardRequest();
this.mockMvc.perform(get("/v1/card/list?"));
}
}
First - Remove the #Configuration annotation from your controller. It doesn't belong here.
Second - Consider using Mockito while testing, since you have a service injected in your controller. Your updated test class should look something similar as below
#RunWith(MockitoJUnitRunner.class)
public class CardApiTest {
private MockMvc mockMvc;
#InjectMocks
private CardManagementController cm;
#Mock
private ICardService cardService;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(cm).build();
// Instantiate cardListRequest and cardListResponse here
when(cardService.listCards(cardListRequest)).thenReturn(cardListResponse);
}
#Test
public void testList() throws Exception{
this.mockMvc.perform(get("/v1/card/list?"));
}
}
Let know in comments if you need further info / assistance.

Categories

Resources