I'm currently taking the angular tutorial using Wisdom framework as back end. As a consequence, I run end-to-end tests using Fluentlenium, as the wisdom framework doc states.
My test for step 3, although dead simple, doesn't pass.
Full test can be found at github : Step03IsImplementedIT
However, here is the offending extract (around lines 30)
#Test
public void canTestPageCorrectly() {
if (getDriver() instanceof HtmlUnitDriver) {
HtmlUnitDriver driver = (HtmlUnitDriver) getDriver();
if(!driver.isJavascriptEnabled()) {
driver.setJavascriptEnabled(true);
}
Assert.assertTrue("Javascript should be enabled for Angular to work !", driver.isJavascriptEnabled());
}
goTo(GoogleShopController.LIST);
// Et on charge la liste des téléphones
FluentWebElement phones = findFirst(".phones");
assertThat(phones).isDisplayed();
FluentList<FluentWebElement> items = find(".phone");
assertThat(items).hasSize(3); // <-- this is the assert that fails
}
Failure message :
canTestPageCorrectly(org.ndx.wisdom.tutorial.angular.Step03IsImplementedIT) Time elapsed: 2.924 sec <<< FAILURE!
java.lang.AssertionError: Expected size: 3. Actual size: 1.
at org.fluentlenium.assertj.custom.FluentListAssert.hasSize(FluentListAssert.java:60)
at org.ndx.wisdom.tutorial.angular.Step03IsImplementedIT.canTestPageCorrectly(Step03IsImplementedIT.java:33)
From that failure, I guess the angular controllers weren't loaded.
How can I make sure they are ? And how can I have a working test ?
Turned out the error wasn't the expected one ... Well, it was, but in a hidden fashion.
HtmlUnitDriver, as one may be aware, is a pure Java implementation of a browser and, as such, has some limitations.
One of its limitation is Javascript interpretation, which seems to go awfully bad with angular ....
To make long things short, the simplest way to fix that is to replace the default driver with firefox one which implies
setting fluentlenium.browser to firefox
make sure driver loads correctly (since firefox.exe should be on path when trying to use its driver) by adding a small assert at the beginning of the test
Final test is then
assertThat(getDriver()).isInstanceOf(FirefoxDriver.class);
goTo(GoogleShopController.LIST);
FluentList<FluentWebElement> items = find("li");
FluentLeniumAssertions.assertThat(items).hasSize(3);
fill("input").with("nexus");
await();
items = find(".phone");
FluentLeniumAssertions.assertThat(items).hasSize(1);
fill("input").with("motorola");
await();
items = find(".phone");
FluentLeniumAssertions.assertThat(items).hasSize(2);
Related
Windows 10 Pro
Latest Simulator
Java Swing Project
I would like to execute "Vector a1 = (Vector) Storage.getInstance().readObject(filePath);"
In a Java Swing Application running on Windows 10 platform, I tried import CodenameOne.jar in Swing package, however when executing above code, get null pointer exception in Storage.getInstance()
Is there a way to execute this in Swing?
Thoughts?
Best Regards.
Thanks, I did not init the Display, however "Display.init(Object m)" requires an Object Argument and the Init method is deprecated.
Can you please provide me the codenameone Display dependencies?
And perhaps a java Swing snippet of code to initialize Display in order to execute Storage.getInstance().readObject(filePath)
Thoughts?
Best Regards
Thanks, Passing init(working directory) solved the Exception thrown.
Here is the Code snippet used to allow me to execute:
Storage.getInstance().readObject(filePath).
String filePath = incSrv.Pwd();// gets working directory
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Display.init(filePath);
String fileName = "A1-MMA.properties";
Vector a1 = (Vector) Storage.getInstance().readObject(filePath);
}
});
} catch (Exception e) {
}
And it does appear to work,
However I am left with a blacked out form that appears modal.
How can I avoid this or dispose it?.
FYI: What I am creating here is a work around for serializing Vector in Codenameone. I Save Vector to file using "Storage.getInstance().writeObject(Path, Vector)"
I convert the file to bytes and write it to the Swing Server VIA socket.
Using Storage.getInstance().readObject(file) on the Swing Server I have deserialize the object into the Vector from my app.
This appears to work well and is more efficient than the current method I use to deliver complex Vectors from the app to the Swing Server.
Can you please let me know if you see a red flag with this workaround?
Like The ability to Storage.getInstance().readObject(file) on the Swing Server may go away?
This method will save a lot of time in movind Vector data to and from the App/Server.
Thoughts Best Regards
Storage.getInstance().readObject(file) // (A1ServiceSrv.java:571)
Caused this Exception:
java.lang.NullPointerException
at com.codename1.io.Storage.init(Storage.java:89)
at com.codename1.io.Storage.getInstance(Storage.java:112)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:571)
Regards
12/11/2021:
Thanks Shai,
I am including in my classpath CodenameOne.jar with update date of 12/11/2021 after CN1 refresh.
Getting Same null pointer exception.
Passing in Path "C:\Src1\A1-Arms\A1-Server\A1-MMA.properties" (Absolute Path)
Also Tried "A1-MMA.properties", however I don't think Codenameone knows where my home path is since we are not initializing it as we did with
Display.init("Current Working Directory where files reside");
This is the Fresh Stack Trace w/o calling Display.init (12-20-2021)
java.lang.NullPointerException at
com.codename1.ui.Display.getResourceAsStream(Display.java:3086)
at com.codename1.io.Log.print(Log.java:327)
at com.codename1.io.Log.logThrowable(Log.java:299)
at com.codename1.io.Log.e(Log.java:285)
at com.codename1.io.Storage.readObject(Storage.java:271)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:596)
vector = (Vector) Storage.getInstance().readObject(filePath); // (A1ServiceSrv.java:596)
This is hopefully fixed by this commit: https://github.com/codenameone/CodenameOne/commit/72bf283bdaaefe5207bb9fd6787578e3ef61522c if not let me know with a fresh stack
I have some tests with WebDriverSampler in Jmeter that work correctly with chromedriver. It is a selenium script that opens a web page and checks that it contains a series of elements. Everything works right until I've tried with the chromedriver headless option.
In this case I get the exception "Expected condition failed: waiting for presence of element located by: By.xpath: ..." as if that element did not exist yet to be loaded. I do not know what can happen, because if I stop using the headless option, if everything works correctly and find the element that really exists.
This is an example of code used(it works without the headless option):
var wait = new support_ui.WebDriverWait(WDS.browser, 30);
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.browser.get('http://mi-app/');
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento_existente')));
WDS.log.info('OK')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail');
WDS.log.error(e.message)
}
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento2_existente')));
WDS.log.info('OK2')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail2');
WDS.log.error(e.message)
}
WDS.sampleResult.sampleEnd();
I hope someone can help me with this problem, because I need to use the headless option. Thank you very much for your time.
You can print the page source to jmeter.log file by using the following function:
WDS.log.info(WDS.browser.getPageSource())
Or even save it into a separate file like:
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('test.html'), WDS.browser.getPageSource())
Or take screenshot on failure like:
WDS.browser.getScreenshotAs(org.openqa.selenium.OutputType.FILE).renameTo(new java.io.File('test.png'))
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information.
Also be aware that if the machine where you run your Selenium tests doesn't have GUI you can still normally launch browsers using i.e. Xvfb on Linux or under Local System account on Windows
All my angular e2e tests using protractor with cucumber are running smooth and fine on my machine. But as soon as I run the tests on the build server, I get an error
ElementNotVisibleError: element not visible
Session info: chrome=51.0.2704.84
Driver info: chromedriver=2.21.371459
platform=Windows NT 6.1 SP1 x86_64
In the beginning, I thought this has something to do with timing, some asynchronous stuff that is happening but after hours of debugging I can finally reproduce the bug even on my local machine.
Minimizing the window is not enough but if I quickly drag the mouse to make the window as small as possible, I get this error. So it is just a matter of "window size".
Thus the error message is quite ok, but how are protractor meant to
run on a build server?
And why are some tests passing? Protractor seems to "see" something on the build server, thus
I tried
browser.driver.manage().window().maximize();
I tried
browser.manage().window().setSize(1920, 1200);
and I tried to change my code as suggested here and I tried a lot of more (hopeless) things. Nothing worked.
My big question now: How can I run a protractor test in a stable fashion on a build server (in my case TFS) when there is a rightmost button I want to click on some page?
Short code sample:
browser.get(browser.baseUrl + '#/somePage').then...
element(by.id(buttonId)).click();
Thank you!
UPDATE:
The main reason for my problems was the fact that the screen resolution while running the test on the build server had a width of 1024 and thus setSize(1920, 1200) failed. For that reason I now added an output of the current resoltuion in the onPrepare function, so that I will get a hint in the future:
onPrepare: function () {
browser.executeScript('return { height: screen.availHeight, width: screen.availWidth, top: screen.availTop, left: screen.availLeft};').then(function (result) {
console.log("Screen resolution: ");
console.log(result);
});
browser.manage().window().setSize(1920, 1200);
Of course this could be extended a little bit to throw an exception or something like this.
Sometimes, we need to bring the desired element into view in order to avoid "Element not visible" error. We can do that in two general ways:
use "browser actions":
var elm = element(by.id("buttonid"));
browser.actions().mouseMove(elm).click().perform()
scroll into view:
var elm = element(by.id("buttonid"));
browser.executeScript("arguments[0].scrollIntoView();", elm.getWebElement());
Also linking this answer that has a nice set of things you can try to tackle the problem.
We run nightly regression scripts using Specflow. Was wondering if there is a way to log the specflow console logs to a file. Since it runs at night, we are not sure about the step where the failure occurred.We do use ReportUnit to convert the nunit xml to html. Will be good to have those console logs in the html too.
you can add hooks which execute before scenario steps ([BeforeStep] and [AfterStep]) and log in there. You can access the ScenarioStepContext to get details of the current step.
A lot has changed with SpecFlow in the last 6 years. Specifically SpecFlow logs each step (along with whether it passes or fails) to the standard output. You can also generate test results files using whichever unit test framework you want. That being said, I did come across a use case where the existing logging that SpecFlow does was not working with Azure DevOps. For my case, I had passing tests, which periodically ran extremely slow. In Azure DevOps release pipelines, a passing test does not get the standard output saved for viewing later. I needed to log the date/time for when a step began, and when it finished.
A before/after step hook using the ScenarioContext object was how I got this logging to work:
[Binding]
public class Hooks
{
[BeforeStep]
public void BeforeStep(ScenarioContext scenario)
{
var stepInfo = scenario.StepContext.StepInfo;
var stepText = $"{stepInfo.StepDefinitionType} {stepInfo.Text}";
// log 'stepText' some place
}
[AfterStep]
public void AfterStep(ScenarioContext scenario)
{
var stepInfo = scenario.StepContext.StepInfo;
var stepText = $"{stepInfo.StepDefinitionType} {stepInfo.Text}";
// log 'stepText' some place
}
}
So I've been using EasyMock's class extension for a while now. All of a sudden I'm getting this exception, but only when I run the entire test suite:
java.lang.IllegalStateException: 0 matchers expected, 1 recorded.
at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:42)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:34)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:26)
at org.easymock.internal.RecordState.invoke(RecordState.java:64)
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:24)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:56)
at org.easymock.classextension.internal.ClassProxyFactory$1.intercept(ClassProxyFactory.java:74)
at com.protrade.soccersim.data.emulator.matrix.PositionCategoryMatrix$$EnhancerByCGLIB$$c5298a7.getPossession(<generated>)
at com.protrade.soccersim.data.emulator.stats.team.PossessionCalculatorUnitTest.testDeterminePossessionHomeWin(PossessionCalculatorUnitTest.java:45)
The code involved is this little beauty (trimmed a bit):
#Before
public void setUp() throws Exception {
homeTeam = createMock( PositionCategoryMatrix.class );
awayTeam = createMock( PositionCategoryMatrix.class );
...
}
#Test
public void testDeterminePossessionHomeWin() {
expect(homeTeam.getPossession()).andReturn( 0.15151515 );
expect(awayTeam.getPossession()).andReturn( 0.01515152 );
replay( homeTeam, awayTeam );
...
}
The exception is being thrown on the first expect. And it really doesn't make sense. It says it's getting a matcher, but the method doesn't even take an argument. And odd enough it's only during test suites! I'm creating a new mock in the #Before, so it shouldn't be inheriting anything from somewhere else (not that some other method would have a matcher on it)
So, any ideas?
I was sick and tired of seeing this with each new legacy code base with EasyMock I had to work with. Write one new EasyMock test by the book and all of the sudden random tests start failing because of Matchers never captured. So I went looking how EasyMock stores those Matchers. It makes use of a final class LastControl, in that class are a few threadlocals where different things get stored. One of those was for the Matchers. Luck has it that there is a static method on there to pull all the Matchers from the threadlocal that where still on there. So this gave me this idea (with help of a collegue, thanks Sven, he wanted credit)
/**
* Base class to make sure all EasyMock matchers are cleaned up. This is not pretty but it will work
*
* #author N069261KDS
*
*/
public class BaseTest {
#Before
public void before(){
LastControl.pullMatchers();
}
#After
public void after(){
LastControl.pullMatchers();
}
}
Basicly let your test that fail with the Matchers error extend from this class and you'll be sure the Matchers are cleaned. Note this IS A WORKAROUND. The offending tests should have been written right in the first place. But if you have to wade through 5000+ tests , this is the lesser of two evils. I hope this will help people out !
While it's true that this can be a spurious message resulting from a "silly" EasyMock bug, it is also very likely to be due to invalid usage of the EasyMock API. In my case the message arose from this JUnit 3.8 test (and like you, this only happened when I ran my entire suite of tests, and only via Maven, not Eclipse):
public void testSomething() {
// Set up
MyArgumentType mockArg = (MyArgumentType) EasyMock.anyObject(); // bad API usage
// Invoke the method under test
final String result = objectUnderTest.doSomething(mockArg);
// Verify (assertions, etc.)
...
}
Instead of using anyObject(), I should have used createMock(MyArgumentType.class) or one of its variants. I don't know what I was thinking, I've written millions of these tests and used the API correctly.
The confusing bit is that the test that fails with the "wrong number of matchers" message isn't necessarily (or ever?) the one in which you used the API wrongly. It might be the first test executed after the buggy one that contains a replay() or verify() method, but I haven't verified this experimentally.
I had the same error message. I was (accidentally) using an isA() declaration in the call on the class under test
I.e.
classUnderTest.callStateChanged(calls, isA(LoggingOnlyListener.class));
when I meant:
classUnderTest.callStateChanged(calls, new LoggingOnlyListener());
And it was the test AFTER this one that failed every time.
I just ran into this problem, and I think I managed to figure it out. For me it was due the the previous test (that's in a different Class), where I was (incorrectly) using an EasyMock matcher in an Assert.assertEquals method.
It seems EasyMock couldn't complain about the extra matcher reported until the first expects methods was called.
I am running into a similar problem. From what I observed, even method returns are matched using Matchers. So if your first method fails for any reason, the matcher for the return match is still in the stack. That could be one reason why you are seeing 1 matchers recorded even when your method doesn't take any argument. Basically, the first method invocation never returned a value.
Which version of Easymock are you using?
I read a post about the release of v.2.5.2 and previuous versions might have a
dumb bug on the capture
try to use Easymock 2.5.2+