Selenium - TestNG - Running groups using Code - java

I'm making a GUI for use of TestNG, currently I have a dropdown box which uses then allows you to press a button which I want to run a group of tests
#Test(groups = {"Group1"})
public void Test()
//Test Data
#Test(groups = {"Group1"})
public void Test2()
//Test Data
#Test(groups = {"Group2"})
public void Test3()
//Test Data
I'm currently running this code via the run configurations and calling the group to run there.
Is there any way I can do this via a button press so the user can press run Group1 and then run Group2 in an executable program?

You can create a synthetic testng.xml in the Java code using the group inputs. But this might get messy with large size testng.xml.
You can also call testng from the command line (Have to figure out this from your GUI code) which has many parameters available like include groups, exclude groups etc etc.
java org.testng.TestNG testng1.xml [testng2.xml testng3.xml ...] -groups "grp1,grp2"
Refer to [http://testng.org/doc/documentation-main.html#running-testng}

You can make use of BeanShell feature that TestNG provides for doing this. You can define a JVM argument that reads the value set using the drop down selected option and then run it.
You can read more about using Beanshell and TestNG from this blog post that I created.

Related

how to print list of files selected in windows console in java

I have the requirement to print the full path and file names of files selected in windows directory.
the approach I have taken is
1. create key in registry to give option in context menu
2. attached the context menu option to execute my java program
now the issue I have ,
I want to select a few files ,
1. then right click on it
2. then execute my java program
3. and have the list of files selected in my java program as an input
i am not able to achieve point 3
any guidance how to approach it or better alternative
I think there is 2 possible approaches here.
You can custom Send to context menu, it supports passing multiple selected files. I prefer this one. It's quite simple to implement.
For example:
Ex.java
import java.io.IOException;
public class Ex {
public static void main(String[] args)
throws IOException {
for (String argument : args) {
System.out.println(argument);
}
System.in.read();
}
}
Compile it to Ex.class.
Create a shortcut named Test Send To in C:\Users\[username]\AppData\Roaming\Microsoft\Windows\SendTo point to:
"path\to\java.exe" -cp "path\to\Ex.class folder" Ex
Now try selecting multiple files and then right-click Send To > Test Send To, you will see the list of selected files onscreen.
You can implement interprocess communication to tell the existing instance that you want to add more files to proceed.

JUnit test case failed

I have a simple test case:
public class FileManagerTest {
String dirPath = “/myDir/”
#Before
public void setUp() {
mFileManager = MyFileManager.getInstance();
}
#Test
private void testPersistFiles() {
System.out.println(“testPersistFiles()…”);
//it deletes old files & persists new files to /myDir/ directory
boolean successful =mFileManager.persistFiles();
Assert.assertTrue(successful);
}
#Test
public void testGetFiles() {
System.out.println(“testGetFiles()…”);
mFileManager.persistFiles();
//I double checked, the persistFiles() works, the files are persisted.
List<File> files = mFileManager.getFilesAtPath(dirPath);
Assert.assertNotNull(files); //Failure here!!!!
}
#Test
public void testGetFilesMap() {
System.out.println(“testGetFilesMap()…”);
mFileManager.persistFiles();
Map<String, File> filesMap = mFileManager.getFilesMapAtPath(dirPath);
Assert.assertNotNull(files);
}
}
The persistFiles() function in FileManager delete all files under /myDir/ then persist files again.
As you see above, I have a System.out.println(…) in each test function. When I run it , I can see all the prints in the following order:
testGetFilesMap()…
testGetFiles()…
testPersistFiles()…
However, test is failed at testGetFiles(). Two things I don't understand:
I don’t understand, it is failed at testGetFiles() why I can still see the print testPersistFiles() which sounds like even it is failed, it doesn't stop running, but continues to run the next test testPersistFiles()? What is happening behind the scene in JUnit test case??
Another thing I don’t understand is why testGetFiles() is failed? I can see log that the persistFiles() has persisted files. Why it got null after that?
I don’t understand, it is failed at testGetFiles() why I can still see the print testPersistFiles() which sounds like even it is failed, i
That is how unit testing works. Each test should be isolated and working using only its set of data. Unit test frameworks run every test so you can see which parts of the system work and which do not, they do not stop on the first failure.
mFileManager.getFilesAtPath(dirPath);
You are not searching the files in the right place
String dirPath = “/myDir/”
Are you sure that this path is ok? with a slash before the directory name?
For each of your tests, JUnit creates a separate instance of that class and runs it. Since you seem to have 3 tests, JUnit will create 3 instances of your class, execute #Before on each of them to initialize state, and then run them.
The order in which they are run is typically the order in which the tests are written but this is not guaranteed.
Now about the print statement - you see that it's the first statement in your test so it will be executed. Then mFileManager.persistFiles(); is executed. For some reason it returns a false and hence the test fails.
As to why it returns false, you can run a local debugger, put a break point at the beginning of that method, single-step and see.

Take screenshot in selenium (java) only in after method

I have created a automation suite in java selenium using testng frame work.Basically in my suite the scenarios are placed in between before and after method.
I want to take the screen shot for each failed and passed test scenario.For that i have created a separate class and calling it in each script to capture the screenshot before the after Method.
The issue that i am facing here is if the scenario is getting failed the script stopped executing and it is not moving to the take screenshot line of code and so it is not capturing the screenshot for the failed ones.
So i want the take screenshot program to be only placed in after method so before the driver quit it will take the screenshot inspite of the scenario result of pass/fail.
I have written code for nearly 20 scenario using testng.
Can some one tel me the code in the after method only to take the screenshot without so much effecting the code which i have written.
The screenshot program should only be in the after method so it will capture teh screen before driver quit.
Make sure you catch exceptions so you won't exit the code prematurely.
For example, this is how I take screenshots after every test run (passed or failed). I use the exception value (if any) to dynamically name the screenshot files.
First, an example test method:
[DataSource("System.Data.SqlClient", "Data Source=DEV338\\X2B;Initial Catalog=SeleniumDb;Integrated Security=True",
"dbo.F_single_ErkenningAannemerKlasse1", DataAccessMethod.Sequential), TestMethod]
public void erkenningAannemerKlasse1()
{
try
{
frontUser.erkenningAannemerKlasse1(data);
}
catch (Exception e)
{
exception = e.Message + " " + e.StackTrace;
}
}
Then this method executes after every test. Default behaviour in Microsoft UnitTest framework, in this case.
[TestCleanup()]
public void Cleanup()
{
frontUser.takeScreenshot(data.get("testnaam"), data.get("datarow"), exception);
frontUser.closeBrowser();
}

How do I open a new project and perspective in SWTBot plug-in test?

For example: I want to "test" Eclipse-CDT. I can't do it using Java code so I need to import a C-project. I didn't found it in Run Configurtion therefore I:
* Create SWTBot Test Plug-in
* Record a sequence of actions via SWTBot Test Recorder:
** Import a C-project
** Change perspective
** Do stuff (run program and check registers for exapmles)
* Insert recorded actions into #Test method
* Run As > SWTBot Test
Here is a problem. SWTBot fails at picking imported project showing various changing errors (mostly "WidgetNotFoundException" at expanding package view or picking imported project from project tree and "NullPointerException" at the same point). Testing code looks like
#Test
public void test() {
bot.menu("File").menu("Import...").click();
bot.tree().expandNode("General").getNode("Existing Projects into Workspace").select();
bot.button("Next >").click();
bot.comboBox().setText("C:\\Sandbox\\JavaWorkspace\\CDTtest");
bot.button("Browse...").click();
bot.button("Finish").click();
bot.toolbarButtonWithTooltip("&Restore").click();
bot.tree().getTreeItem("CDTtest").getNode("main.c").select();
bot.menu("Project").menu("Build Project").click();
bot.menu("Run").menu("Debug").click();
bot.tree().getTreeItem("General Registers").expand();
bot.menu("Run").menu("Step Over").click();
}
Is there more appropriate way to described things? Or maybe a more appropriate tool for that?
It seems like the generated code doesn't include anything about switching to another property. It's possible that there is no recording rule existing for this action. You may need to tweak your test manually to add this missing operation.

How to test a web page using selenium through a desktop application?

I need to test a webpage via desktop application, I'm trying to use
the selenium IDE, I had sucess to create the test cases, but I'm not
able to execute them on java.
I've been looking for something helpful, but I can't find any help at all.
Thank you
A framework that has been created for just this cause, (it's in Java) can be downloaded here or you can check the project out from github here.
This project was designed to be very simple, yet very effective. This type of framework is a "free version" of my interpretation of a framework that I use every day in production-type environments.
There is a sample test that is enclosed in the project named SampleFunctionalTest.java. Assuming you follow the ReadMe to the T, you should have no problem getting started.
Here is what a test would look like in this framework.
#Config(url = "http://ddavison.github.io/tests/getting-started-with-selenium.htm", browser = Browser.FIREFOX) // You are able to specify a "base url" for your test, from which you will test. You may leave `browser` blank.
public class SampleFunctionalTest extends AutomationTest {
/**
* You are able to fire this test right up and see it in action. Right click the test() method, and click "Run As... jUnit test".
*
* The purpose of this is to show you how you can continue testing, just by taking the semi colon out, and continuing with your test.
*/
#Test
public void test() {
// click / validateAttribute
click(props.get("click"))
.validateAttribute(props.get("click"), "class", "success") // validate that the class indeed added.
// setText / validateText
.setText(By.id("setTextField"), "woot!")
.validateText(By.id("setTextField"), "woot!") // validates that it indeed set.
// check / uncheck
.check(By.id("checkbox"))
.validateChecked(By.id("checkbox")) // validate that it checked
.check(props.get("radio.2")) // remember that props come from <class name>.properties, and are always CSS selectors. (why use anything else, honestly.)
.validateUnchecked(props.get("radio.1")) // since radio 1 was selected by default, check the second one, then validate that the first radio is no longer checked.
// select from dropdowns.
.selectOptionByText(By.xpath("//select[#id='select']"), "Second") // just as a proof of concept that you can select on anything. But don't use xpath!!
.validateText(By.id("select"), "2") // validateText() will actually return the value="" attr of a dropdown, so that's why 2 works but "Second" will not.
.selectOptionByValue(By.cssSelector("select#select"), "3")
.validateText(props.get("select"), "3")
// frames
.switchToFrame("frame") // the id="frame"
.validatePresent(By.cssSelector("div#frame_content"))
// windows
.switchToWindow("Getting Started with Selenium") // switch back to the test window.
.click(By.linkText("Open a new tab / window"))
.waitForWindow("Google") // waits for the url. Can also be the you are expecting. :) (regex enabled too)
.setText(By.name("q"), "google!")
.closeWindow(); // we've closed google, and back on the getting started with selenium page.
}
}
You should create an instance of a WebDriver and call methods on the instance of that object.
An easy example is shown here: http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
I hope you have created the script in webdriver.
Now in the script recorded by the selenium ide you have three methods called
setup, testSomeName and tearDown.
From the very basic: to run this script all you need to do is create a main method in the same class and in that you need to call these methods in the same order as specified above.
After that you just need to run that program.
Here is an example to make it more clear:
public class p_adjcb {
public void setUp() throws Exception {
}
public void testP_adjcb() throws Exception {
}
public void tearDown() throws Exception {
}
public static void main(String[] args) {
p_adjcb obj = new p_adjcb();
try {
obj.setUp();
obj.testP_adjcb();
obj.tearDown();
} catch (Exception ex) {
}
}
}
If you get any compiler error make sure you have downloaded the selenium-standalone-server.jar file and added it to your class path.
This is a very basic start. Later on you may need to use som framework like junit.
Hope it helps.

Categories