Junit test case in springboot giving response null in get API - spring-boot

Trying to implement junit testcases in my Spring-boot application. the test class ProjectStatusControllerTestjava defined a simple get function for fetching data using mockmvc framework provided by junit 4. The API gives response 200 OK, but no data in data object of the json response, refer below the code snippet and the response of the server .Using maven command mvn test -Dtest=ProjectStatusControllerTest for execution.
#RunWith(SpringRunner.class)
#WebMvcTest(ProjectStatusController.class)
#ContextConfiguration(classes = {ProjectStatusController.class,ProjectStatusService.class, ProjectStatusServiceImpl.class,
ProjectStatusRepository.class, SpringSecurityonfig.class, RestAuthenticationEntryPoint.class,
JwtParser.class, OodlesProperties.class, LeadDataView.class})
#AutoConfigureWebMvc
public class ProjectStatusControllerTest {
#MockBean
private ProjectStatusService projectStatusService;
#Autowired
MockMvc mockMvc;
#Test
public void getAllProjectStatus()throws Exception {
String str = "http://localhost:9000/" +UrlMappings.GET_ALL_PROJECT_STATUS;
String authToken = "eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINHNJQUFBQUFBQUFBSTFVejI4YlJSUitkbXdTa2ladGs3WVVTa3Fob0o2NmRrTHNKSXFFNnRpbTNiRGVMVjViVVMxVjBYaDNiRSt6M2xsbXhvN05BY1NGQXozQUFRNGN1Q0loVmVLSXhCMGhvWjQ0Y29FRFZcLzRGNE0zYWE3Y24yTU8zNzcxOXYrZmJlZklYWktXQVd4N3ZHNXo3QVpXR3pcL3VFaFlhazNrQXdOVGJjcWRDVVZOeUdwVjgrXC91NzBlaHBXVzdCSVE5SU9xSTlTajBpTGRsUUx6akhwRGlJcWhreHljUVFaUWNMVEkzaGhnTEdtYjBHV1l1NUF3YnIxaUF4SkxpQmhOK2Nxd2NMdWdZWDUrcEZOK3ZRRCtBaFM2TnNWeEUrVU5QTVZYSGdteXVKeHpGSkVwRHpqd2srQ0JNY1pacTREeFlLY3hhUkMxM055MXBnWnU2Y3hYRGNXSmpWSFVRcFNNSGxtYndVWCt5U2tWUGJ1VEJmRXVJTFYyc1IybzBaOEVpcElsWEdMYTdx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TR2Vm4rQmZKUWdnMkdCUUFBIiwic3ViIjoibWFuZWVzaEBvb2RsZXMuaW8iLCJyb2xlcyI6WyJST0xFX0FOT05ZTU9VUyIsIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX09PRExFUyIsIlJPTEVfQkQiLCJST0xFX0hSIiwiUk9MRV9DT05URU5UV1JJVEVSIiwiUk9MRV9JTSIsIlJPTEVfUE1PIiwiUk9MRV9BQ0NPVU5UUyIsIlJPTEVfREFTSEJPQVJEX0FETUlOIiwiUk9MRV9SRVNPVVJDSU5HX0FETUlOIiwiUk9MRV9BQ0NPVU5UU19BRE1JTiIsIlJPTEVfTEVHQUwiLCJST0xFX1FVRVNUSU9OX0JBTksiLCJST0xFX0xFR0FMX0FETUlOIiwiUk9MRV9CRF9DRU5UUkFMIl0sImdyYWRlIjoiQyIsImlzU3RlYWx0aE1vZGUiOmZhbHNlLCJyYW5rIjoxLCJpZCI6MSwidHlwZSI6InVzZXIiLCJleHAiOjE2NTYzNDA3MzAsInVzZXJJZCI6MSwiaXNTdXBlcnZpc2VyIjp0cnVlLCJpYXQiOjE2NTYzMDgzMzB9.RAu-YFfCyD90gXMkk9BIvS5GU046QIKhETBkdgoziWk";
mockMvc.perform(get(str)
.header(HttpHeaders.AUTHORIZATION,authToken)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk()).toString();
}
}
Response ::::::
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/projectStatus/getAllProjectStatus
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Authorization:"eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINHNJQUFBQUFBQUFBSTFVejI4YlJSUitkbXdTa2ladGs3WVVTa3Fob0o2NmRrTHNKSXFFNnRpbTNiRGVMVjViVVMxVjBYaDNiRSt6M2xsbXhvN05BY1NGQXozQUFRNGN1Q0loVmVLSXhCMGhvWjQ0Y29FR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attrs = {}
Handler:
Type = com.oodles.controller.projectStatus.ProjectStatusController
Method = com.oodles.controller.projectStatus.ProjectStatusController#getAllProjectStatus(String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"data":[],"message":"No Record Found","timestamp":1656308435497,"status":200,"isSuccess":true} -----NO DATA IN JSON
Forwarded URL = null
Redirected URL = null
Cookies = []

Related

Junit rest controller throws login url instead of Actual model and view

I am tring to test my spring-boot rest controller, its giving the login page instead of actual result. its giving 302 status, I have given the controller code , test case and error given by the junit.Please have look all the code and let me you need any other information
Controller
#GetMapping("{userId}/edit/{todoId}")
public ModelAndView updateTodo(#PathVariable Long userId, #PathVariable Long todoId) {
User user = userService.findById(userId);
ModelAndView model = new ModelAndView("todo-form.jsp");
model.addObject("userId",userId);
return model;
}
Junit test
#ExtendWith(SpringExtension.class)
#SpringBootTest
#AutoConfigureMockMvc
class UserApiControllerTest {
#DisplayName("Test updateTodo Api")
#Test
public void updateTodo() throws Exception {
mockMvc.perform(get("/1/edit/2"))
.andExpect(status().isOk());
}
ERROR
MockHttpServletRequest:
HTTP Method = GET
Request URI = /1/edit/2
Parameters = {}
Headers = []
Body = null
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/1/edit/2]}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 302
Error message = null
Expires:"0", Location:"http://localhost/login"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = http://localhost/login
Try disabling spring security as it's redirecting to login page.
#AutoConfigureMockMvc(addFilters = false)
secure=false should work too but may be deprecated depending on your version of Spring

I'm trying to make a unit test for a Spring Controller but i'm getting 404 instead of 200

I'm trying to make a unit test for a Spring Controller but i'm getting 404 instead of 200
Here is my controller method :
#Timed
#PostMapping(value = "/aaa/bbb", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#ApiOperation(value = "")
public ModelAndView redirectPsnResponseForCgu(#RequestParam final MultiValueMap<String, String> formData,
final ModelMap model) {
....
}
Here is my test method
#Test
public void should_intercept_and_redirect() throws Exception {
final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("pa", "test");
formData.add("par", "test");
formData.add("param", "test");
final String content = AppUtils.printJson(formData.toSingleValueMap(), true);
this.mvc.perform(
post("/base-url/aaa/bbb")
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.params(formData)
.header("origin", "*"))
.andExpect(status().isOk());
}
This is the test results. I don't understand why the 404 status ! Could you see if i'm missing something in my code ?
MockHttpServletRequest:
HTTP Method = POST
Request URI = /base-url/aaa/bbb
Parameters = {pa=[test], par=[test], param=[test]}
Headers = [Content-Type:"application/x-www-form-urlencoded", origin:"*"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Access-Control-Allow-Origin:"*", Access-Control-Allow-Credentials:"false", Access-Control-Allow-Methods:"GET, POST, DELETE, PUT, OPTIONS", Access-Control-Max-Age:"3600", Access-Control-Allow-Headers:"Origin, Accept, Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, username", Access-Control-Expose-Headers:"Content-Length, Content-Disposition, Authorization"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404

Spring Boot Web Test - 404 Not found

I am trying to test the Controller of a very simple GET request with #WebMvcTest but I'm getting 404 instead of 200 and the console does not give me anything useful to understand what is going on.
I've put a breakpoint at the beginning of the controller but it never arrives. If I run the application, the endpoint works as expected.
Here's my controller:
#RestController
public class RegistroClienteController {
#GetMapping("/api/registro-cliente")
public ResponseEntity<Void> crearCliente() {
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
And here's my test:
#RunWith(SpringRunner.class)
#WebMvcTest(RegistroClienteController.class)
#ContextConfiguration(classes = { SecurityConfig.class })
public class RegistroClienteControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
UserDetailsService userDetailsService;
#Test
public void test() throws Exception {
//#formatter:off
mockMvc
.perform(get("/api/registro-cliente"))
.andExpect(status().isOk());
//#formatter:on
}
}
And console's output:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/registro-cliente
Parameters = {}
Headers = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = [[Cookie#624b3544 name = 'XSRF-TOKEN', value = 'f9d63654-4e21-4d41-b3bb-6767703268b5', comment = [null], domain = [null], maxAge = -1, path = '/', secure = false, version = 0, httpOnly = false]]
I was having the same error and after hours of searching found that the error is due to controller not being registered. The problem is described here.
Apparently, the following is not enough.
#WebMvcTest(controllers = {<ControllerToTest>.class})
You need to do,
#WebMvcTest(controllers = {<ControllerToTest>.class})
#Import(<ControllerToTest>.class)
I can try to change the annotations
#WebMvcTest(RegistroClienteController.class)
to
#SpringBootTest(classes = {your application class}.class)

Empty content body in checking exception scenarios with mockmvc

Overview:
I am going to test bad request (400) with a customized error message in Spring MVC Test. The test gets 400 as status; however the content body is empty.
The code snippets are as follows:
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
memberServiceController.setMemberDetailsApiController(mockMemberDetailsApiController);
memberServiceController.setResourceMessage(mockResourceMessage);
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilter(new ShallowEtagHeaderFilter())
.apply(documentationConfiguration(restDocumentation))
.build();
}
#Test
public void getMemberDetails_whenStoreIdIsNull_setStatusToBadRequest() throws Exception {
Mockito.doReturn("storeId is empty").when(mockResourceMessage).getMessage(MEMBER_ERROR_INVALID_STOREID);
mockMvc.perform(get(URL)
.header(REQUEST_HEADER_COOKIE, DEFAULT_COOKIE_VALUE)
.param(REQUEST_PARAM_MEMBERSHIP_IDENTIFIER, "MEMBER1"))
.andDo(MockMvcResultHandlers.print())
.andDo(document("memberServices/GetMemberDetailsNullStoreId",
requestHeaders(
headerWithName(REQUEST_HEADER_COOKIE).description(REQUEST_HEADER_COOKIE_DESCRIPTION)
),
requestParameters(
parameterWithName(REQUEST_PARAM_MEMBERSHIP_IDENTIFIER).description(REQUEST_PARAM_MEMBERSHIP_IDENTIFIER_DESCRIPTION)
)))
.andExpect(status().isBadRequest())
.andExpect(content().string(containsString("storeId is empty".toLowerCase())))
.andReturn().getResponse();
}
The raised exception is as follows:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /retailer1/memberDetails
Parameters = {membershipIdentifier=[MEMBER1]}
Headers = {Cookie=[SESSION=67421bc3-36da-4b64-9aca-94edf57211f6]}
Handler:
Type = com.blss.retailServices.memberServices.restServices.MemberRestController
Method = public org.springframework.http.HttpEntity<org.springframework.hateoas.Resource<com.blss.retailServices.memberServices.models.MemberDetailsResponseModel>> com.blss.retailServices.memberServices.restServices.MemberRestController.getMemberDetails(com.blss.retailServices.memberServices.models.MemberModel)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = com.blss.retailServices.InvalidRequestException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Response content
Expected: a string containing "storeid is empty"
but: was ""
The generated response in API Doc with asciidoc is as follows:
HTTP/1.1 400 Bad Request
Question:
Now I would appreciate it if anyone can help me find way to get bad request with my customized exception message ("storeId is empty") in order to be added to generated API documentation and have something like bellow as generated response in API documentation:
HTTP/1.1 400 Bad Request,
storeId is empty
The problem was related to exception handling in my code. I forgot to add GlobalControllerExceptionHandler class which is our exception handler to #SpringApplicationConfiguration in my test class. So after adding it as follows my problem solved:
#SpringApplicationConfiguration(classes = {
MemberRestControllerTest.class,
MemberRestController.class,
ResourceResultProcessor.class,
GlobalControllerExceptionHandler.class
})
public class MemberRestControllerTest {
...
}

MockMvc Test Spring throws org.springframework.web.HttpMediaTypeNotSupportedException

I am getting the follow exception org.springframework.web.HttpMediaTypeNotSupportedException trying to test a Json Controller.
The method in controller is:
#RequestMapping(value = "/report", method = RequestMethod.PUT)
public #ResponseBody DatosJsonVO report(#RequestHeader(value = "hash", required = true) String hash,
#RequestBody ReportVO report) {
}
My test method is the following:
#Test
public void reportarPreguntaSesionInvalida() throws Exception {
ReportVO report = new ReportVO();
report.setIdQuestion(1);
report.setIssue("Wrong answer");
mockMvc.perform(put("/json/report").header("hash", "123456789")
.accept(MediaType.APPLICATION_JSON).content(asJsonString(report))).andDo(print())
.andExpect(content().string("{\"code\":2,\"message\":\"Session error\",\"data\":null}"));
}
But, I get this response:
MockHttpServletRequest:
HTTP Method = PUT
Request URI = /json/report
Parameters = {}
Headers = {hash=[8.16615469E8], Accept=[application/json]}
Handler:
Type = com.controller.json.QuestionsJsonController
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 415
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
My Spring Version is 4.0.0.RELEASE
You need to set the content type.
mockMvc.perform(put("/json/report")
.header("hash", "123456789")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(asJsonString(report))).andDo(print())
.andExpect(content().string("{\"code\":2,\"message\":\"Session error\",\"data\":null}"));
mockMvc.perform(put("/json/report").header("hash", "123456789")
.accept(MediaType.APPLICATION_JSON)
.content(asJsonString(report)))
.contentType(MediaType.APPLICATION_JSON)
.andDo(print())
.andExpect(content().string("{\"code\":2,\"message\":\"Session error\",\"data\":null}"));

Resources