I have the following function:
public class NorthboundApiLogicTest {
#Test
public void testIfParametersValuesAreCorrect() {
String body = "{\"exception\":\"world\",\"error\":\"Not Found\",\"message\":\"hello\""
+ ",\"timestamp\":\"2020-01-07T12:26:48.334386Z\",\"status\":\"404\"}";
try {
JSONAssert.assertEquals("{message:hello, exception:world, status:403, error:Not Found}",
body, false);
} catch (Exception e) {
System.err.println(e);
}
System.out.println(body);
}
}
I run this test with Maven, and strangely it pass successfully.
However, it should not, because I assert that status=403 but the value is 404. What am I doing wrong?
It's failing to parse the JSON before it even performs an assertion on the structure, and you're simply logging that via your catch.
catch (Exception e) {
System.err.println(e);
}
You need to let that exception be thrown from the method, or catch it and call fail() with an appropriate message.
And then fix the issue of your non-parseable JSON, of course!
Related
I want to add a filter to an existing project, and don't expect my filter to affect the original process in abnormal case. In any cases, the original filter should be executed.
So, I want to know, how should I process when I catch an Exception:
throw the Exception
catch the Exception and call chain.doFilter();
do nothing, like the following code:
if (filter != null) {
filter.doFilter(req,resp,chain);
// should I catch the exception here?
} else {
chain.doFilter(req,resp);
}
Thanks all.
nest your try-catch block inside if(filter!=null)
For instance:
if(filter != null){
try{} catch (Exception e){
//do something
}
}
Also you can use finally after catch for any clean up or code you want to run no whether an exception is caught or not.
I am trying to catch an exception and return a value to my client page, but I get ClassCastException and it is not returning any value.
My code snippet-
#RequestMapping(value = "/config/MyFile/data", method = RequestMethod.GET)
#ResponseBody
public List<Myfile> getAllFlatFileTrafficCops()
{
try
{
return MyFileServices.getAlldata();
}
catch (final ResourceAccessException r)
{
final Throwable flatfileTrafficCopStatus;
flatfileTrafficCopStatus = r.getCause();
return (List<FlatFileTrafficCop>) flatfileTrafficCopStatus;
}
}
All you can do in this case in Exception situation catch the exception and encapsulate it in your meaningful custom exception and propagate it back to caller function and for web display meaningful error text.
Always propagate exceptions back to caller. For debug you might want to add a log statement over there.
catch (final ResourceAccessException r)
{
CustomException cException = new CustomException(r);
throw cException;
//OR
FlatFileTrafficCop emptyObj= new FlatFileTrafficCop(Witherr);
//add that in a list and return
}
first is ClassCastException child of ResourceAccessException? No, so your catch will not work, if you want to catch ClassCastException you have to make 2nd catch for it
catch (final ClassCastException e){}
but while you are using spring no need to catch it like this you can use #ExceptionHandler instead
Am working on selenium Automation
I want to know the name of which elements is not found when test cases got failed instead of getting object not found with property By.id("Login")
am expecting output like Object not found LoginButton(Customized name which i will give in code) when test cases fails due to defect
public static void logonCustomerPortal() throws Exception{
Thread.sleep(5000);
driver.findElement(By.xpath("//a[#id='nav_login']/span")).click();
Thread.sleep(2000);
}
I am new to Automation. Can anyone please help me ?
try to use try catch like this :
public void urmethod(){
try {
//do your code
}catch (Exception e){
e.printStackTrace();
}
}
this will print details of your error, in other words, what kind of error, in which line it fails...etc
How can I retrieve a compile time error message from StringTemplate as a String?
This code for instance:
STGroup stg = new STGroup('<', '>');
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
if (compiledTemplate == null)
System.out.println("Template is invalid");
Will simply log something like "invalid came as a complete surprise to me", but I want to display this error message in my UI.
I can access the ErrorManager with stg.errMgr. I expected a method like getErrors() here, but there isn't...
You could set an error listener for the group, which would allow you to catch the error, and then pass it to the UI from there.
This answer tells you more about implementing an STErrorListener. The example they give doesn't compile since they're throwing checked exceptions from within the ErrorListener. Perhaps a better approach would be to handle the errors directly inside the listener, or you could just throw a RuntimeException so you could catch the errors when you call stg.defineTemplate(...).
public class MySTErrorListener implements STErrorListener {
...
#Override
public void compileTimeError(STMessage msg) {
// do something useful here, or throw new RuntimeException(msg.toString())
}
...
}
If you were to throw the RuntimeException you could then catch it when you define the ST:
stg.setListener(new MySTErrorListener());
try{
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
} catch (Exception e)
{
// tell the UI about the error
}
I want to achieve writing to log file with Log4j.
I have found one easy solution - surround test body with try - catch:
#Test(groups = "GMAIL_PAGE")
public void testAllMailLink() {
try {
List<WebElement> allMessages = page.takeAllMessage();
page.clickInboxLink();
List<WebElement> inboxMessages = page.takeInboxMessage();
page.clickDraftLink();
List<WebElement> draftMessages = page.takeDraftMessage();
Assert.assertTrue(allMessages.containsAll(inboxMessages),
"All messages doesn't contains all inbox messages");
Assert.assertTrue(allMessages.containsAll(draftMessages),
"All messages doesn't contains all draft messages");
log.info("test is passed");
} catch (Exception e) {
log.error(e);
}
}
But it has some drawbacks - this test is always passed, even if it fails.
It is ok if I work on my machine and able to see console. But what to do when this test is pushed to Continuous Integration server?
Does exist any other way to write info into log file, when test fail?
Add Assert.fail() below your log.error(e):
catch (Exception e) {
log.error(e);
Assert.fail();
}
By the way, you're calling Logger#error(Object), which uses e.toString(). In this case, it is better to use a descriptive message and then pass the exception to get the respective stacktrace:
catch (Exception e) {
log.error("Some descriptive message should go here.", e);
Assert.fail("Some descriptive message should go here as well.");
}