Why Doesnt my 'AssertEquals()' method Fail? - selenium-webdriver

Why doesn't my assert method fail when the two strings clearly do not match?
public void checkHomepageURL_Test1() throws Exception {
basePage.loadHomePage();
try {
System.out.println("inside try block");
Assert.assertEquals("Actual String Expected", "Im Wrong!");
System.out.println("inside try block SECOND!!");
} catch (Throwable e) {
System.out.println("BETA!!!!!!" + e.getMessage());
} finally {
System.out.println("All over now!");
}
}
New Examaple

When an assert fails it throws an Throwable. Since you have your assert inside a try-catch block, when that Throwable is raised, it will be captured by the catch block, your program will log ""BETA!!!!!!" + e.getMessage()" and then it will finish properly.
You should either:
remove your try catch block
catch Exception instead of Throwable
(the first option is the proper one for a test AFAIK)
If you remove the Catch, your error will be printed as follows in your console.
org.junit.ComparisonFailure:
Expected :Actual String Expected
Actual :Im Wrong!
<Click to see difference>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.scouto.test.checkHomepageURL_Test1(test.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Related

Investigate Java.Lang.NullPointerException on a Codename One iOS app

Today I tried to investigate this issue: https://github.com/codenameone/CodenameOne/issues/2975
I'm writing here to ask how I can find exactly what goes wrong. This bug is frustrating.
Basically, on iOS only, I have this error, that happens after some random app usage:
java.lang.NullPointerException
at com_codename1_ui_Form.pointerReleased:3758
at net_informaticalibera_cn1_simpleapi_OuterForm.pointerReleased:360
at com_codename1_ui_Component.pointerReleased:4679
at com_codename1_ui_Display.handleEvent:2289
at com_codename1_ui_Display.edtLoopImpl:1214
at com_codename1_ui_Display.mainEDTLoop:1132
at com_codename1_ui_RunnableWrapper.run:120
at com_codename1_impl_CodenameOneThread.run:176
at java_lang_Thread.runImpl:153
I've overridden the pointerReleased method to see if x and y are acceptable values when the previous exception is thrown, it seems so:
#Override
public void pointerReleased(int x, int y) {
try {
super.pointerReleased(x, y);
} catch (Exception ex) {
Log.p("OuterForm.pointerReleased ERROR, x->" + x + ", y->" + y + ", https://github.com/codenameone/CodenameOne/issues/2975");
Log.e(ex);
SendLog.sendLogAsync();
}
}
Using that override, that is equivalent to the crash protection feature, after the first time that this exception happens the TextArea components are not more usable: the tap on them doesn't open the VKB.
In short, there is a NullPointerException inside the iOS port of Form.pointerReleased: how can I discover which line of that method throws the exception? I hope to find info that can help for the bug resolution.
The problem is that the code of the method public void pointerReleased(int x, int y) of the class Form is all inside a try... finally, that hides the actual cause of the exception.
To get the actual cause, I used the following override in the BaseForm class of my app, that extends Form and that I use as superclass for all other Forms:
#Override
public void pointerReleased(int x, int y) {
try {
Component cmp = instance.getResponderAt(x, y);
if (cmp != null) {
cmp.pointerReleased(x, y);
}
} catch (Exception ex) {
Log.p("BaseForm.pointerReleased ERROR, x->" + x + ", y->" + y + ", https://github.com/codenameone/CodenameOne/issues/2975");
Log.e(ex);
SendLog.sendLogAsync();
}
}
As expected, this gave me the actual cause of the bug, that was inside a lambda expression of a TextArea actionListener: more specifically, the issue was a revalidate on an Container reference that can be null in some circumstances (oddly, this happens only on iOS). After that, I removed the previous override (that broke some functionalities), I fixed my code preventing the revalidate on a null object (with an if condition) and the bug disappeared (I've done a test with a long usage of the app).

NotifyBuilder.matches() always times out

I would like to validate the retry logic built into my Camel route definition.
from(somewhere)
.errorHandler(
defaultErrorHandler()
.log("something")
.maxRedeliveries(3)
)
.to(somewhere-else)
To do so I wrote test deliberately raise an exception.
int counter = 0;
#Test
public void simulateError() throws Exception {
NotifyBuilder nb = new NotifyBuilder(mock.getCamelContext()).whenDone(3).create();
mock.whenAnyExchangedReceived(
new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
counter++;
throw new FooException("Error during processing: " + counter);
}
}
);
template.sendBody(somewhere, "some message");
boolean matches = nb.matches(8, TimeUnit.SECONDS);
assertEquals("Exception raised", 3, counter);
}
Now this works fine. However if I assert on matches by adding
assertTrue(matches)
It fails. In other words, the NotifyBuilder's match criterion is never met and it always times out.
Why is that? Is it because retries don't count as exchange deliveries?
What is the canonical way to test that redelivery is attempted the expected number of times?
Closing the loop & answering my own question.
Firstly - Indeed retries don't count towards done-messages.
As noted by Claus Ibsen, the preferred (shortest?) solution is to verify that the mock receives the expected number of messages. That will be max_retries + 1 (4 in my case). So the working code looks like
#Test
public void simulateError() throws Exception {
/*
* Verify the error handling logic by checking the number of messages that are delivered.
* It must be 1 + number of retries.
*/
mock.expectedMessageCount(maxRetries + 1);
mock.setAssertPeriod(6000); // Necessary to ensure the message count is treated as an exact number.
mock.whenAnyExchangeReceived(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("Intercepted to-endpoint");
ProcessingFailedException e = new FooException("Error during processing");
exchange.setException(e);
throw e;
}
});
producerTemplate.sendBody(umbFrom, "Hello world");
mock.assertIsSatisfied();
}

Hystrix: cannot trip circuit breaker

Assuming i use the default Hystrix configurations:
CircuitBreakerRequestVolumeThreshold=20
CircuitBreakerErrorThresholdPercentage=50
MetricsRollingStatisticalWindowInMilliseconds=10000ms
I assume this means that within a 10 sec window, the circuit will break if there are 10 handled exceptions within 20 consecutive requests.
I have a class called MyCommand which extends HystrixCommand. I create 20 objects of it and call execute on each sequentially. But I don't seem to trip the circuit because it never goes into my getFallback method. I expected the 20th execute to trip the circuit. Where am i going wrong?
int i=0;
public MyObject run() throws Exception {
i++;
try {
throw new Exception("Handled exception "+i);
} catch (Exception e) {
System.out.print("Catch "+i);
}
return null;
}
If you handle the exceptions within the command then the circuit breaker will not open. In your run method do not catch the exception.

Code for unhandled exception not working

I am using following code for unhandled exceptions.
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
e.Handled = true;
Error.Exp = e.ExceptionObject;
(RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source = new Uri("/Error.xaml", UriKind.Relative);
}
This code should direct the control to Error.xaml page but it goes to visual studio with the error message of the exception (even after commenting out if block). What is wrong here ?
The source of error is
GeneralTransform generalTransform1 = canvas1.TransformToVisual(start_rec);
Error message was
"Argument exception was unhandled. The parameter is incorrect."
try
{
// do something with your crash , report it or write log
}
catch
{
}
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
the debug go to the place exception throw .

How to mock out Thread.sleep() with JMockit?

I have the following code:
class Sleeper {
public void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
How do I test, with JMockit, that Thread.currentThread().interrupt() is called if Thread.sleep() throws an InterruptedException?
Interesting question. A bit tricky to test because mocking certain methods of java.lang.Thread can interfere with the JRE or with JMockit itself, and because JMockit is (currently) unable to dynamically mock native methods such as sleep. That said, it can still be done:
public void testResetInterruptStatusWhenInterrupted() throws Exception
{
new Expectations() {
#Mocked({"sleep", "interrupt"}) final Thread unused = null;
{
Thread.sleep(anyLong); result = new InterruptedException();
onInstance(Thread.currentThread()).interrupt();
}
};
new Sleeper.sleep();
}
As of JMockit 1.43, this is impossible
JMockit 1.43 added this commit, which checks if you are trying to mock a thread and blacklists it. Now you will get this exception:
java.lang.IllegalArgumentException: java.lang.Thread is not mockable

Resources