Junit test cases for delete - junit

public UserNoteDefination deleteByNoted (UserNoteDefination request, LogOTO log) { log.setComponent("ClientRequestService.deleteByNoted") UserNoteDefination response = new UserNoteDefination()
String tablame request.getTabName() String noteCd request.getNoteCd();
if (tablame.equalsIgnoreCase("UND TABLE"))
try (
userNoteDefRepository.deleteById(noteCd); response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServicefonstants. INFO LEVEL, log);
catch (Exception e)
response.setMsg("Error");
log.setPayload("[FROH:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR
I have attached the code

Related

Junit test cases for delete operation with try and catch block - handling Exception

public UserNoteDefination deleteByNoteCd (UserNoteDefination request, LogDTO log) {
log.setComponent("ClientRequestService.deleteByNoteCd");
UserNoteDefination response new UserNoteDefination();
String tabllame = request.getTabName();
String noteCd-request.getNoteCd();
if (tabName.equalsIgnoreCase("UND_TABLE"))
{
try
userNoteDefRepository.deleteById(noteCd);
response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServiceConstants.INFO LEVEL, log);
}
catch (Exception e){
response.setMsg("Error");
log.setPayload("[FROM:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR LEVEL, log);
}
return response;
}
This is my junit code in mockito
#Test public void deleteByNoteCd() throws Exception {
LogDTO log = new LogDTO(); log.setComponent("ClientRequestService.getClientRequest");
UserNoteDefination response = new UserNoteDefination();
response.setNoteCd("TEST7");
response.setMsg("Completed");
response.setTabName("UND TABLE");
UserNoteDefination rval - service.deleteByNoteCd(response, log);
assertNotNull(rval);
}
I'm unable to cover the exception part. Cab someone help

How to send a message to errorChannel when an exception occurs in spring integration?

Hi I have an spring integration flow where my message traverse through multiple Deserialization, transformation and serialization process.
I am unable to handle any exception that are thrown during the process. I have defined my error channel as below. How to interrupt the integration flow and send the message to error channel?
================ error channel ===============
#Bean("errorChannel")
public MessageChannel errorChannel() {
return new DirectChannel();
}
#Bean
#Router(inputChannel = "errorChannel")
public ErrorMessageExceptionTypeRouter handleError(){
ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter();
Map<String, String> mappings = new HashMap<>();
mappings.put(RuntimeException.class.getName(), "someChannel");
mappings.put(Exception.class.getName(), "someChannel");
router.setChannelMappings(mappings);
return router;
}
#ServiceActivator(inputChannel = "someChannel")
public void handleErrors(Message<?> message) {
LOGGER.info(" error caught in some channel {}", message);
}
============== error emitting channel ====================
#Bean
#ServiceActivator(inputChannel = "JSON_to_IM_in_Process")
public AbstractReplyProducingMessageHandler json_to_im_svc() throws Exception {
AbstractReplyProducingMessageHandler mh = new AbstractReplyProducingMessageHandler () {
#Override
public Message<?> handleRequestMessage(Message<?> inputMessage) {
String inputRecord = inputMessage.getPayload().toString();
Map<String, Object> newheader = new HashMap<String, Object>();
InputModel result = null;
******if(true) throw new RuntimeException("forcefully Exception ");******
try {
ObjectMapper mapper = new ObjectMapper();
result = mapper.readValue(inputRecord, InputModel.class);
newheader.put("Exception_Status", "Passed");
Message<?> outMsg = MessageBuilder.withPayload(result).copyHeaders(inputMessage.getHeaders())
.copyHeaders(newheader).build();
LOGGER.info("Deserialized to Input Model -------------->" + outMsg);
return outMsg;
} catch (Exception e) {
newheader.put("Exception_Status", "Failed");
String excep = "Exception in translating inputFormat to Object";
Message<?> outMsg = MessageBuilder.withPayload(excep).copyHeaders(inputMessage.getHeaders())
.copyHeaders(newheader).build();
LOGGER.info("Exception in translating inputFormat to Object", e.getMessage());
return outMsg;
}
}
I want to catch the exception in the errorChannel but unable to do so. I want to break the integration flow from the exception I want to execute "someChannel" and stop and send to the outboundRequest channel.
If the exception is inside the try{} block it is handled by the catch block. If the exception is outside the try block the stack trace is coming directly on the console.
What I need to do more to catch the exceptiopn in the errorChannel ?

How to throw an exception for closing resource in try with resources?

I want to try with resources block(PrintWrtiter or FileWriter) to throw an exception on closing resource, So i can print it.
public PrintWriter func throws CustomException{
String filename = "file.txt";
try(PrintWriter feedError = new PrintWriter(new FileWriter(filename ,
true))){
feedError.println("writing in a file");
return feedError;
} catch (Exception e){
e.printStackTrace();
Throwable[] supp = e.getSuppressed();
System.Out.Println(supp);
throw new CustomException("file not found");
}
}
Expecting java.lang.Exception: Error when closing PrintWriter or FileWriter

Test cases using mockito

I have below method of a class.
public Response getProb(long Id) throws ResourceException
{
final Response response = new Response();
JSONObject headerObject = new JSONObject();
String message = null;
int status = 0;
try
{
JSONObject getProb = new JSONObject();
getProb.put("id", Id);
if (commonDao.validateIdCheck(getProb))
{
headerObject.put(CommonConstants.LASTMOD_DATE, commonDao.lastModDate(Id));
response.setResource(headerObject);
message="Retuned Successfully";
}
response.setStatus(message, status);
}
catch (JSONException exception)
{
throw new ResourceException(CommonErrorConstants.JSON_EXCEPTION, exception);
}
catch (ResourceException exception)
{
throw exception;
}
catch (Exception exception)
{
throw new ResourceException(CommonErrorConstants.GENERAL_EXCEPTION, exception);
}
return response;
}
what will be the junit test cases using mockito which will give 100% code coverage.
These are the cases you can test and achieve 100% coverage:
validateIdCheck returns true
validateIdCheck returns false
your try block throws JSONException
your try block throws ResourceException
your try block throws Exception
a success case where you return a response

Parameter passing via httpgetClient

I need to hit the URL and get the response, but through this method I can get only one message whereas I want to pass multiple values as a response.
Here is the method:
public String getOutputFromUrl(String url)
{
Log.d("in getOutputFromUrl", "getOutputFromUrl");
String[] output = null;
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("in UnsupportedEncodingException", e.toString());
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("in geClientProtocolExceptiontOutputFromUrl", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("in getOutputFromUrl", e.toString());
e.printStackTrace();
}
Log.d("in getOutputFromUrl:output===>>", output);
return output;
}
I want the return type of the method to be String[] or object of any class ,but
output = EntityUtils.toString(httpEntity)
This line accepts only a string; no other object or string array, so I can't keep multiple values in this output variable passed as response from the URL link