java.lang.NoSuchMethodError:
org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/
runner/Description;Ljava/lang/Throwable;)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMĀethod(SpringJUnit4ClassRunner.java:
155)
And written testcase for controller like, newly writing testcases for Spring Controller classes:
TestXController.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:D:/ABC/src/main/webapp/WEB-INF/
xyz-servlet.xml",
"file:D:/ABC/src/main/webapp/WEB-INF/xyzrest-servlet.xml"})
public class TestXController {
#Inject
private ApplicationContext applicationContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private XController controller;
#Test
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
// I could get the controller from the context here
controller = new XController();
}
#Test
public void testgoLoginPage() throws Exception {
request.setAttribute("login", "0");
final org.springframework.web.servlet.ModelAndView mav = handlerAdapter.handle(request, response, controller);
assertViewName(mav, null);
assertAndReturnModelAttributeOfType(mav, "login", null);
}
#Test
public void testgoHomePage(){
org.springframework.web.servlet.ModelAndView mav =null;
request.setAttribute("success1", "1");
request.setAttribute("success", "1");
try {
mav = handlerAdapter.handle(request, response, controller);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertViewName(mav, null);
assertAndReturnModelAttributeOfType(mav, "home",null);
}
Can any one Guide me on this to write test cases for Spring
Controller classes,Or any code samples links.
Thanks & Regards, Venu Gopala Reddy.
Yes, make sure you're using the right version of JUnit. I think there's a mismatch with the Spring test JAR that forces you to use JUnit 4.4.
Related
I have created a Spring Restful Service and Spring MVC application.
Restful Service ::
Restful service returns an entity if its existing in DB. If it doesn't exist It returns a custom Exception information in ResponseEntity object.
It is working as expected tested using Postman.
#GetMapping(value = "/validate/{itemId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<MyItem> validateItem(#PathVariable Long itemId, #RequestHeader HttpHeaders httpHeaders) {
MyItem myItem = myitemService.validateMyItem(itemId);
ResponseEntity<MyItem> responseEntity = null;
if (myItem == null) {
throw new ItemNotFoundException("Item Not Found!!!!");
}
responseEntity = new ResponseEntity<MyItem>(myItem, headers, HttpStatus.OK);
return responseEntity;
}
If the requested Entity does not exist Restful Service returns below.
#ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
System.out.println("In CREEH::ItemNFE");
ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
ResponseEntity<ExceptionResponse> responseEntity = new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND);
return responseEntity;
}
But when I am calling the above service from a spring MVC application using RestTemplate, It is returning a valid object if it exists.
If the requested object does not exist Restful service is returning the exception information but its not reaching the calling(spring MVC) application.
Spring MVC application calls Restful Web Service using Rest template
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();
This is expected behavior. Rest template throws exception when the http status is client error or server error and returns the response when http status is not error status.
You have to provide implementation to use your error handler, map the response to response entity and throw the exception.
Create new error exception class with ResponseEntity field.
public class ResponseEntityErrorException extends RuntimeException {
private ResponseEntity<ErrorResponse> errorResponse;
public ResponseEntityErrorException(ResponseEntity<ErrorResponse> errorResponse) {
this.errorResponse = errorResponse;
}
public ResponseEntity<ErrorResponse> getErrorResponse() {
return errorResponse;
}
}
Custom error handler which maps the error response back to ResponseEntity.
public class ResponseEntityErrorHandler implements ResponseErrorHandler {
private List<HttpMessageConverter<?>> messageConverters;
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return hasError(response.getStatusCode());
}
protected boolean hasError(HttpStatus statusCode) {
return (statusCode.is4xxClientError() || statusCode.is5xxServerError());
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpMessageConverterExtractor<ExceptionResponse> errorMessageExtractor =
new HttpMessageConverterExtractor(ExceptionResponse.class, messageConverters);
ExceptionResponse errorObject = errorMessageExtractor.extractData(response);
throw new ResponseEntityErrorException(ResponseEntity.status(response.getRawStatusCode()).headers(response.getHeaders()).body(errorObject));
}
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
this.messageConverters = messageConverters;
}
}
RestTemplate Configuration - You have to set RestTemplate's errorHandler to ResponseEntityErrorHandler.
#Configuration
public class RestTemplateConfiguration {
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntityErrorHandler errorHandler = new ResponseEntityErrorHandler();
errorHandler.setMessageConverters(restTemplate.getMessageConverters());
restTemplate.setErrorHandler(errorHandler);
return restTemplate;
}
}
Calling Method
#Autowired restTemplate
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
try {
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();
} catch (ResponseEntityErrorException re) {
ResponseEntity<ErrorResponse> errorResponse = re.getErrorResponse();
}
Try using the #ResponseBody annotation on your Exceptionhandler. e.g:
public #ResponseBody ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {... }
You should use Custom Exception Handler to fix your case. It looks like this
#ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public CustomResponseEntityExceptionHandler() {
super();
}
// 404
#ExceptionHandler(value = { EntityNotFoundException.class, ResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
BaseResponse responseError = new BaseResponse(HttpStatus.NOT_FOUND.value(),HttpStatus.NOT_FOUND.name(),
Constants.HttpStatusMsg.ERROR_NOT_FOUND);
logger.error(ex.getMessage());
return handleExceptionInternal(ex, responseError, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
And your code should throw some exception, eg:
if (your_entity == null) {
throw new EntityNotFoundException("said something");
}
If you get this case in somewhere else again, you just throw exception like above. Your handler will take care the rest stuffs.
Hope this help.
I've started your application and works just fine.
Maven :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
The controller class is :
#Controller
public class ValidationController {
#GetMapping(value = "/validate/{itemId}")
public #ResponseBody ResponseEntity<MyItem> validateItem(#PathVariable Long itemId) {
if (itemId.equals(Long.valueOf(1))) {
throw new ItemNotFoundException();
}
return new ResponseEntity<>(new MyItem(), HttpStatus.OK);
}
#ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
System.out.println("In CREEH::ItemNFE");
ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
ResponseEntity<ExceptionResponse> responseEntity = new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
return responseEntity;
}
}
and the test:
#RunWith(SpringRunner.class)
#WebMvcTest(value = ValidationController.class, secure = false)
public class TestValidationController {
#Autowired
private MockMvc mockMvc;
#Test
public void testExpectNotFound() throws Exception {
mockMvc.perform(get("/validate/1"))
.andExpect(status().isNotFound());
}
#Test
public void testExpectFound() throws Exception {
mockMvc.perform(get("/validate/2"))
.andExpect(status().isOk());
}
}
Are you sure the url you are trying to use with RestTemplate is correct?
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
Your get method is #GetMapping(value = "/validate/{itemId}"
If you don't have request mapping at the level of the controller the url should be:
http://localhost:8080/validate/1
Another difference is the missing #ResponseBody on your controller method.
I have got Spring Boot Application and I want to test it. I do not use Spring Controllers, but I use Servlet with service method. Also I have got my configuration class that provides ServletRegistrationBean.
But every time when I try to perform mock request I get 404 error. There is no call to servlet at all. I think that Spring does not find this servlet. How could I fix it? While I am launching app at localhost everything works fine.
Test:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class SpringDataProcessorTest {
#Autowired
private MockMvc mockMvc;
#Test
public void retrieveByRequest() throws Exception{
mockMvc.perform(buildRetrieveCustomerByIdRequest("1")).andExpect(status().isOk());
}
private MockHttpServletRequestBuilder buildRetrieveCustomerByIdRequest(String id) throws Exception {
return get(String.format("/path/get('%s')", id)).contentType(APPLICATION_JSON_UTF8);
}
}
Configuration:
#Configuration
public class ODataConfiguration extends WebMvcConfigurerAdapter {
public String urlPath = "/path/*";
#Bean
public ServletRegistrationBean odataServlet(MyServlet servlet) {
return new ServletRegistrationBean(servlet, new String[] {odataUrlPath});
}
}
MyServlet:
#Component
public class MyServlet extends HttpServlet {
#Autowired
private ODataHttpHandler handler;
#Override
#Transactional
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}
If you really want to use MockMvc to test your code instead of a Servlet use a HttpRequestHandler and use a SimpleUrlHandlerMapping to map it to a URL.
Something like the following.
#Bean
public HttpRequestHandler odataRequestHandler(ODataHttpHandler handler) {
return new HttpRequestHandler() {
public void handleRequest() {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}
}
And for the mapping
#Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setUrlMap(Collections.singletonMap(odataUrlPath, "odataRequestHandler");
return mapping;
}
Another solution would be to wrap it in a controller instead of a servlet.
#Controller
public class ODataController {
private final ODataHttpHandler handler;
public ODataController(ODataHttpHandler handler) {
this.handler=handler;
}
#RequestMapping("/path/*")
public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}
In either way your handler should be served/processed by the DispatcherServlet and thus can be tested using MockMvc.
Working on a spring boot based Rest project I have a controller like this
which calls service and service layer call dao layer. Now I am writing unit test code for controllers. when I run this the error says
java.lang.AssertionError: expected:<201> but was:<415>
I don't know where I am doing wrong:
public class CustomerController {
private static final Logger LOGGER = LogManager.getLogger(CustomerController.class);
#Autowired
private CustomerServices customerServices;
#Autowired
private Messages MESSAGES;
#Autowired
private LMSAuthenticationService authServices;
#RequestMapping(value = "/CreateCustomer", method = RequestMethod.POST)
public Status createCustomer(#RequestBody #Valid Customer customer, BindingResult bindingResult) {
LOGGER.info("createCustomer call is initiated");
if (bindingResult.hasErrors()) {
throw new BusinessException(bindingResult);
}
Status status = new Status();
try {
int rows = customerServices.create(customer);
if (rows > 0) {
status.setCode(ErrorCodeConstant.ERROR_CODE_SUCCESS);
status.setMessage(MESSAGES.CUSTOMER_CREATED_SUCCESSFULLY);
} else {
status.setCode(ErrorCodeConstant.ERROR_CODE_FAILED);
status.setMessage(MESSAGES.CUSTOMER_CREATION_FAILED);
}
} catch (Exception e) {
LOGGER.info("Cannot Create the Customer:", e);
status.setCode(ErrorCodeConstant.ERROR_CODE_FAILED);
status.setMessage(MESSAGES.CUSTOMER_CREATION_FAILED);
}
return status;
}
}
The test for the CustomerController.
public class CustomerControllerTest extends ApplicationTest {
private static final Logger LOGGER = LogManager.getLogger(CustomerControllerTest.class);
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#MockBean
private CustomerController customerController;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
Status status = new Status(200,"customer created successfully","success");
String customer = "{\"customerFullName\":\"trial8900\",\"customerPhoneNumber\": \"trial8900\", \"customerEmailID\": \"trial8900#g.com\",\"alternateNumber\": \"trial8900\",\"city\": \"trial8900\",\"address\":\"hsr\"}";
#Test
public void testCreateCustomer() throws Exception {
String URL = "http://localhost:8080/lms/customer/CreateCustomer";
Mockito.when(customerController.createCustomer(Mockito.any(Customer.class),(BindingResult) Mockito.any(Object.class))).thenReturn(status);
// execute
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post(URL)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(TestUtils.convertObjectToJsonBytes(customer))).andReturn();
LOGGER.info(TestUtils.convertObjectToJsonBytes(customer));
// verify
MockHttpServletResponse response = result.getResponse();
LOGGER.info(response);
int status = result.getResponse().getStatus();
LOGGER.info(status);
assertEquals(HttpStatus.CREATED.value(), status);
}
}
HTTP status 415 is "Unsupported Media Type". Your endpoint should be marked with an #Consumes (and possibly also #Produces) annotation specifying what kinds of media types it expects from the client, and what kind of media type it returns to the client.
Since I see your test code exercising your production code with MediaType.APPLICATION_JSON_UTF8, you should probably mark your endpoint as consuming and producing APPLICATION_JSON_UTF8.
Then you also need to make sure that there is nothing terribly wrong going on in your error handling, because in the process of catching the exceptions generated by your production code and generating HTTP responses, your error handling code may be generating something different, e.g. generating an error status response with a payload containing an HTML-formatted error message, which would have a content-type of "text/html", which would not be understood by your test code which expects json.
Use the below base test class for your setUp and converting json to string and string to json
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = Main.class)
#WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
#Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
Also verify that your post call has happened or not check the below sample
Mockito.doNothing().when(customerServices).create(Mockito.any(Customer.class));
customerServices.create(customer);
Mockito.verify(customerServices, Mockito.times(1)).create(customer);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
I have a unit test to carry out based on the following part of code:
#RequestMapping(value = "/changePass", method = RequestMethod.POST)
public ModelAndView changePass(#ModelAttribute(TAPPLICATION) AppBean applicationBean, BindingResult result, ModelMap model, Principal principal, HttpServletRequest request) throws NSException, SQLException {
// ...
if (applicationBean != null
&& applicationBean.getChangePassDto() != null
&& StringUtils.isNotEmpty(applicationBean.getChangePassDto().getNewPassword())) {
String newPassword = applicationBean.getChangePassDto().getNewPassword();
// ...
}
// ...
The AppBean contains the following getter and setter:
private ChangePassDto changePassDto;
public ChangePassDto getChangePassDto() {
return changePassDto;
}
public void setChangePassDto(ChangePasswordDto changePassDto) {
this.changePassDto = changePassDto;
}
Basically when I execute the unit test the method applicationBean.getChangePassDto() is null but applicationBean is not null. How can I initialise the applicationBean.getChangePassDto() so that it does not return null? I have initialised the other non object parameters with the .param method as it can be seen in my unit test.
I am also using Powermock as unit test framework.
Please find below part of my unit test:
#Before
public void setup() {
request = new MockHttpServletRequest();
request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
response = new MockHttpServletResponse();
session = new MockHttpSession();
request.setSession(session);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
//Added viewResolver to prevent circular view path error
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
this.mockMvc = MockMvcBuilders.standaloneSetup(appController).setViewResolvers(viewResolver).build();
}
#Test
public void changePass_ExpectC() throws Exception {
PowerMockito.doNothing().when(passwordVal).validate(any(User.class), anyListOf(Params.class), any(Object.class),any(Errors.class));
mockMvc.perform(post("/changePass").param("userLogName", "JOHN").param("userLogged", "userLogged").param("password", "password123").param("newPassword", "newPassword123").param("confirmNewPassword", "newPassword123"))
.andExpect(view().name(Constants.DENIED))
.andExpect(status().isOk()
);
}
Any idea how I can intitialise applicationBean.getchangePassDto() so that it is not null?
Thanks in advance for help.
Simply create a new instance of ChangePassDto in your AppBean:
public class AppBean {
private ChangePassDto changePassDto = new ChangePassDto();
public ChangePassDto getChangePassDto() {
return changePassDto;
}
public void setChangePassDto(ChangePasswordDto changePassDto) {
this.changePassDto = changePassDto;
}
// ...
}
You then need to use the full path to the properties in the nested DTO like this:
mockMvc.perform(post("/changePass")
.param("changePassDto.userLogName", "JOHN")
.param("changePassDto.userLogged", "userLogged")
.param("changePassDto.password", "password123")
.param("changePassDto.newPassword", "newPassword123")
.param("changePassDto.confirmNewPassword", "newPassword123"))
.andExpect(view().name(Constants.DENIED))
.andExpect(status().isOk());
I am trying to write a junit for a spring controller whose signature is something like this
#RequestMapping(value = { "/addPharmcyInLookUpTable.form" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
public String processSubmitAddPhl(#ModelAttribute PhrmcyAdmin phrmcyAdmin,
BindingResult result, SessionStatus status,
HttpServletRequest request) throws Exception {
.....
....
}
The junit for this is
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/applicationContext.xml",
"classpath:/puela-app-config.xml" }, inheritLocations = true)
public class AddPharmacyInLookUpTableControllerTest {
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(
AddPharmacyInLookUpTableControllerTest.class);
}
#InjectMocks
private AddPharmacyInLookUpTableController controller;
private static MockHttpServletRequest request;
private static MockHttpServletResponse response;
#Autowired
private HandlerMapping handlerMapping;
#Autowired
private HandlerAdapter handlerAdapter;
#BeforeClass
public static void runBeforeAllTest() throws Exception {
System.out.println("Running one time Setup");
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
private ModelAndView handle(final HttpServletRequest request,
final HttpServletResponse response) throws Exception {
final HandlerExecutionChain handler = handlerMapping
.getHandler(request);
Assert.assertNotNull(
"No handler found for request, check you request mapping",
handler);
final Object controller = handler.getHandler();
for (final HandlerInterceptor interceptor : handlerMapping.getHandler(
request).getInterceptors()) {
if (!interceptor.preHandle(request, response, controller)) {
return null;
}
}
return handlerAdapter.handle(request, response, controller);
}
#Test
public void processRequestAddPhl_post() throws Exception
{
PhrmcyAdmin phrmcyAdmin = new PhrmcyAdmin();
phrmcyAdmin.setPhlCalMailbox("Test");
phrmcyAdmin.setPhlMailPharmacy("FootHill");
request.setMethod("POST");
request.setRequestURI("/addPharmcyInLookUpTable.form");
// Code goes here
MockHttpSession session = new MockHttpSession();
ModelAndView mv = handle(request, response);
assertEquals(mv.getViewName(), "addPhrmcyInTable.view");
}
}
I am trying to send this model object phrmcyAdmin along with the request. Any idea how we can deal with the model object??