How to skip execution of test case from the Hooks in cucumber - selenium

I have to skip execution of the test case #bannerVerificationSMMDView only when the viewPort is Large
#Before
public void beforestartUp(Scenario scenario) throws IOException {
boolean runTest = true;
if (viewPort.contains("LARGE")) {
System.out.println("for Scenario " + scenario.getName() + " tagname are");
List<String> tags = (List<String>) scenario.getSourceTagNames();
for (String tagName : tags) {
if (tagName.contains("bannerVerificationLView"))
runTest = false;
}
try {
Assume.assumeTrue(runTest);
} catch (AssumptionViolatedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Not sure why, but exception is not getting caught

Throw a AssumptionViolatedException to skip the execution of scenario.
#Before(value="#bannerVerificationSMMDView")
public void before(Scenario scenario) {
if(viewPort.contains("LARGE"))
throw new AssumptionViolatedException("Skipping as view is LARGE");
}
If you are on cucumber version 3 plus, you can use a #BeforeStep annotation instead, keep everything else same. This will allow you to run any previous steps in the scenario and if condition is not met then skip the rest of the steps in the scenario

Related

Plugin Development: Eclipse hangs when testing plugin

I am new to developing plugins, and was wondering what causes a test plugin to hang when started i.e. Eclipse is unresponsive.
I know that my code is working as I developed a voice recognition plugin to write to the screen what is said and when I open notepad everything I say is printed to notepad.
So I was wondering, am I missing something in the plugin life-cycle that causes the IDE to hang when my plugin is started?
package recognise.handlers;
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
return null;
}
}
Does the start.startVoiceRecognition() need to be threaded?
Thanks in advance and let me know if you would like to see my manifest/activator etc.
Conclusion
Added a job separate to the UI thread
/*
* Start a new job separate to the main thread so the UI will not
* become unresponsive when the plugin has started
*/
public void runVoiceRecognitionJob() {
Job job = new Job("Voice Recognition Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
TakeInput start = new TakeInput();
try {
start.startVoiceRecognition(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use this to open a Shell in the UI thread
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
As shown start.startVoiceRecognition() is running in the UI thread, and it will block the UI thread until it is finished and the app will be unresponsive during that time. So if it is doing a significant amount of work either use a Thread or use an Eclipse Job (which runs work in a background thread managed by Eclipse).
To unblock your UI you have to use Display thread.
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
MessageDialog.openInformation(shell, "Your Popup ",
"Your job has finished.");
}
});
return null;
}
You can use Display.getDefault().asyncExec() as mentioned above, so your UI will be unblocked, while your non UI code will be executing.

play, java8 - re-use test fake application in tests?

is there anyway to stop the actor system from shutting down and starting up between tests?
I keep getting akka exceptions complaining about the actor system being down.
I can mock/stub to get rid of the reliance on the fake app but it needs a bit of work - hoping to be able to just start one static test application up and run different things in the app.
Eg I have a (crappy) test like this - can I somehow re-use the running app between tests? it still seems to shut down somewhere along the line.
running(Fixtures.testSvr, HTMLUNIT, browser -> new JavaTestKit(system) {{
F.Promise<TestResponseObject> resultPromise = client.makeRequest("request", "parameterObject", system.dispatcher());
boolean gotUnmarshallingException = false;
try {
Await.result(resultPromise.wrapped(), TotesTestFixtures.timeout.duration());
} catch (Exception e) {
if ((e instanceof exceptions.UnmarshallingException)) {
gotUnmarshallingException = true;
}
}
if(gotUnmarshallingException == false) fail();
}});
You can try to get rid of the running method (it stops the testserver at the end) and initialize a testserver by yourself, but I don't know if Akka will be available to you:
#BeforeClass
public static void start() {
testServer = testServer(PORT, fakeApplication(inMemoryDatabase()));
testServer.start();
// Maybe you dont ned this...
try {
testbrowser = new TestBrowser(HTMLUNIT, "http://localhost:" + PORT);
} catch (Exception e) {
}
}
#Test
public void testOne() {
new JavaTestKit() {
// (...)
}
}
#AfterClass
public static void stop() {
testServer.stop();
}

How to write Unit test for Action that throw HttpException with StatusCode 404

I have a below action in a controller which throw HttpException with status code 404:
public async Task<ActionResult> Edit(int id)
{
Project proj = await _service.GetProjectById(id);
if( proj == null)
{
throw new HttpException(404, "Project not found.");
}
}
To test this scenario, I have written below test case where I am catching AggregationException and rethrowing InnerException which is expected as HttpException:
[TestMethod]
[ExpectedException(typeof(HttpException),"Project not found.")]
public void Edit_Project_Load_InCorrect_Value()
{
Task<ActionResult> task = _projectController.Edit(3);
try
{
ViewResult result = task.Result as ViewResult;
Assert.AreEqual("NotFound", result.ViewName, "Incorrect Page title");
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
This test run succefully and return ExpectedException. I have two questions here:
Is this right approach for writing unit test or there is more
gracious way of testing it.
Is this possible to check in Unit Test
that user is getting correct error page( NotFound in this case).
There is a nicer way to test this. We wrote a class called AssertHelpers.cs that has this method in it. The reason this is nicer than ExpectedException is that ExpectedException does not actually verify it was thrown, it just allows the test to pass when it is thrown.
For example, if you change your 404 code to return 200 your test will not fail.
public static void RaisesException<TException>(Action dataFunction, string exceptionIdentifier = null)
{
bool threwException = false;
try
{
dataFunction();
}
catch (Exception e)
{
threwException = true;
Assert.IsInstanceOfType(e, typeof(TException));
if (exceptionIdentifier != null)
Assert.AreEqual(exceptionIdentifier, e.Message);
}
if (!threwException)
Assert.Fail("Expected action to raise exception with message: " + exceptionIdentifier);
}

How to avoid Selenium runtime exception UnreachableBrowserException

I am using Selenium with GhostDriver and sometimes I got the error:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died., caused by exceptions include java.lang.InterruptedException
It happens when using findbyElement, findByElements, get, or click methods of Selenium.
It does not happens always and not in the same places, but it happens more frequently on Windows environments.
Does anyone knows how can I avoid this exception?
I tried adding more time while using waits but it did not work.
To avoid this exception, you can override the get method. (Usually, this exception append once)
public class CustomPhantomJSDriver extends PhantomJSDriver {
#Override
public void get(String url) {
int count = 0;
int maxTries = 5;
while (count < maxTries) {
try {
super.get(url);
break;
} catch (UnreachableBrowserException e) {
count++;
}
}
if (count == maxTries) {
throw new UnreachableBrowserException(url);
}
}
}
This worked for me: http://matejtymes.blogspot.co.uk/2014/10/webdriver-fix-for-unreachablebrowserexc.html
Use it anywhere you would otherwise use PhantomJSDriver (it covers all situations: get, click, findByElement, ...)
public class FixedPhantomJSDriver extends PhantomJSDriver {
private final int retryCount = 2;
public FixedPhantomJSDriver() {
}
public FixedPhantomJSDriver(Capabilities desiredCapabilities) {
super(desiredCapabilities);
}
public FixedPhantomJSDriver(PhantomJSDriverService service, Capabilities desiredCapabilities) {
super(service, desiredCapabilities);
}
#Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
int retryAttempt = 0;
while (true) {
try {
return super.execute(driverCommand, parameters);
} catch (UnreachableBrowserException e) {
retryAttempt++;
if (retryAttempt > retryCount) {
throw e;
}
}
}
}
}

How do I force a method in Groovy to throw an exception

I wanted to write a test for a method in Groovy that throws an IOException. The only way for me to simulate this in the test is to force the method to throw this exception
This is what the original code looks like:
public void cleanUpBermudaFiles(RequestMessage requestMessage)
{
final File sourceDirectory = new File(preferenceService.getPreference("bermuda.landingstrip") + File.separator + requestMessage.getWorkflowId().getValue());
if(sourceDirectory!=null && sourceDirectory.exists())
{
deleteDirectory(sourceDirectory);
}
else
{
LOG.error("Directory must exist in order to delete");
}
}
private void deleteDirectory(File directoryToDelete)
{
try {
FileUtils.deleteDirectory(directoryToDelete);
} catch (Exception e) {
LOG.error("Failed to delete Bermuda files directory located at:" + directoryToDelete.getPath() + "with an exception" + e.getMessage());
}
}
MY TEST: (I'm looking for a way to make deleteDirectory throw IOException)
public void testCleanUpBermudaFailure()
{
workflowId = new WorkflowId("123456")
workflowDirectory = new File(srcDirectory, workflowId.value)
workflowDirectory.mkdir()
File.createTempFile('foo','.lst', workflowDirectory)
def exception = {throw new IOException()}
expect(mockRequestMessage.getWorkflowId()).andReturn(workflowId)
expect(mockPreferenceService.getPreference("bermuda.landingstrip")).andReturn(srcDirectory.path)
replay(mockPreferenceService, mockRequestMessage)
fileCleanUpService.preferenceService = mockPreferenceService
fileCleanUpService.metaClass.deleteDirectory = exception
fileCleanUpService.cleanUpBermudaFiles(mockRequestMessage)
verify(mockPreferenceService, mockRequestMessage)
assert srcDirectory.listFiles().length == 0, 'CleanUp failed'
}
If the service class is a Groovy class, you would want to mock FileUtils like:
FileUtils.metaClass.static.deleteDirectory = { File f -> throw new IOException() }
However, as ataylor pointed out, you cannot intercept calls if it's a Java class. You can find a nice blog post about it here.
You are mocking a no-arg call to deleteDirectory, but the real deleteDirectory takes one argument of type File. Try this:
def exception = { File directoryToDelete -> throw new IOException() }
...
fileCleanUpService.metaClass.deleteDirectory = exception