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

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

Related

Junit test cases for delete

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

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 ?

Exception : could not prepare statement

This is the Controller class
#RequestMapping(value = "/addToView", method = RequestMethod.POST, consumes = "application/json")
public Response addToView(#RequestBody ClassA classA){
return service1.addToview(classA);
}
This is the DAO class
public Response addToview(ClassA classA){
try{
s=sf.openSession();
tx=s.beginTransaction();
String q="INSERT INTO abc(rollNo,name,english) VALUES("+classA.getRollNo()+","+classA.getName()+","+classA.getEnglish()+")";
System.out.println(q);
Query query=s.createSQLQuery(q);
query.executeUpdate();
response.setStatus(200);
response.setMessage("succesfull");
tx.commit();
}
catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
response.setStatus(500);
response.setMessage("unsuccesfull");
tx.rollback();
} finally {
s.close();
}
return response;
}
Here the query is getting executed in sql console but when i am trying
implement it in the code it is not working it is giving error saying
could not prepare statement

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

How to re-throw exception in AspectJ around advise

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error log and continue the flow by re-throwing the exception.
I tried to achieve this by following but eclipse says "Unhandled Exception type".
Code-against whom AspectJ is to used :-
public interface Iface {
public void reload() throws TException;
public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;
public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;
public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;
public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}
Code AspectJ :-
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;
StopWatch watch = new Slf4JStopWatch();
try {
ret = proceed();
} catch (UserNotFoundException e) {
ex = e;
throw e;
} catch (ResumeNotFoundException e) {
ex = e;
throw e;
} catch (Throwable e) {
ex = e;
throw new RuntimeException(e);
} finally {
watch.stop(thisJoinPoint.toShortString());
if (ex != null) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
numEx++;
}
}
return ret;
}
}
Please help why this AspectJ is not working.
you can avoid catching the exceptions and just use a try/finally block without the catch.
And if you really need to log the exception you can use an after throwing advice, like this:
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
StopWatch watch = new Slf4JStopWatch();
try {
return proceed();
} finally {
watch.stop(thisJoinPoint.toShortString());
}
}
after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
}
}
I'm afraid you cannot write advice to throw exceptions that aren't declared to be thrown at the matched join point. Per: http://www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html :
"An advice declaration must include a throws clause listing the checked exceptions the body may throw. This list of checked exceptions must be compatible with each target join point of the advice, or an error is signalled by the compiler."
There has been discussion on the aspectj mailing list about improving this situation - see threads like this: http://dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html
but basically what you will need to do is different advice for each variant of exception declaration. For example:
Object around() throws ResumeServiceException, ResumeNotFoundException, TException:
call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {
that will advise everywhere that has those 3 exceptions.
There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect
Object around(...): ... {
try {
return proceed(...);
}
catch (RuntimeException ex) {
throw ex;
}
catch (Error err) {
throw err;
}
catch (Throwable thr) {
Rethrower.rethrow(thr);
throw new IllegalStateException("Should never get here", thr);
}
}
/**
* Ugly but safe workaround: We need to be able to propagate checked exceptions,
* despite AspectJ around advice supporting specifically declared exceptions only.
*/
private static class Rethrower {
public static void rethrow(final Throwable exception) {
class CheckedExceptionRethrower<T extends Throwable> {
#SuppressWarnings("unchecked")
private void rethrow(Throwable exception) throws T {
throw (T) exception;
}
}
new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
}
}