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
Related
I am coming to an issue where I am trying to check if output folder is there and if not create one in my code below. So, I tried doing that way as shown in my code but I dont know if its the proper a way of doing it? can you please advise. thanks for the help.
here is my code:
String outputFolder2 = Printer.getOutputFolder();
File outFileTwo = new File(outputFolder2);
if (!outFileTwo.exists()) {
if (!outFileTwo.mkdir()) {
System.out.println("Failed to make directory for: " + outputFolder2);
}
}
To check if the directory exists:
Files.isDirectory(Paths.get("/the/path"))
To create dir if not exists:
Files.createDirectories(Paths.get("/the/path"))
Simply use
dirPathFileObj.mkdir();
From java.io.File;
If the method detects that no such directory exists, it will automatically create one. Otherwise, it will simply do nothing in terms of File creation.
It's recommended to use the nio package for new code that interacts with files -- it's faster, and easier to code for. Here's how I would write that code, in the form of a junit test that I ran to verify it:
#Test
public void testSomething() {
Path dirPath = Paths.get("C:/I/do/not/exist");
Path filePath = dirPath.resolve("newFile.txt");
try {
assertFalse(Files.exists(dirPath));
dirPath = createDirectories(dirPath);
filePath = Files.createFile(filePath);
assertTrue(Files.exists(filePath));
} catch (IOException iox) {
iox.printStackTrace();
} finally {
try {
Files.deleteIfExists(filePath);
Files.deleteIfExists(dirPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will create C:\I\do\not\exist\newFile.txt, then delete C:\I\do\not\exist, (leaving C:\I\do\not\). For production code, you'd want to remove the asserts and fill in those catch clauses
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!
If anyone know how to take screenshot of failed test/methods in selenium webdriver using reportNG then please help.
If you provide code then its helpfull or provide some ideas to solve this problem.
Thanks in advance.
Yes, It is possible.
WebDriver firfoxDriver = new FirefoxDriver();
firfoxDriver.get("https://stackoverflow.com/");
File file = ((TakesScreenshot)firfoxDriver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(file, new File("E:\\Data\\ss.png"));
Or You can use this:
#AfterMethod(alwaysRun=true)
public void catchExceptions(ITestResult result){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
String methodName = result.getName();
if(!result.isSuccess()){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File((String) PathConverter.convert("failure_screenshots/"+methodName+"_"+formater.format(calendar.getTime())+".png")));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Well It's depend on your framework that where the control is going after failing the method.
Suppose in your case it is going in catch exception block then copy that code in catch block.
File file = ((TakesScreenshot)firfoxDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("YOUR PATH"+Filename+.JPG));
You can use Itestlistener in testng to take screenshot. testng has an in built function by which you can take screenshot when it fails.
Just create a seperate listerner class and paste this code:
public class listeners implements ITestListener{
//This "Base " is the main class where you can pass the result of test case and write the //code for screenshot
//I cam creating an object so I can access the method that I created for screenshot in this base class.
//I am also getting the result name so I can identify which test case it got failed
Base b = new Base();
public void onTestFailure(ITestResult result) {
try {
//Getting the result name by result.getName() method
b.getScreenshot( result.getName());
System.out.println("The Failed test is=="+result.getName());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I created this getScreenshot method in the base class and passing the result name
public class Base {
public WebDriver InitializeDr() throws IOException {
//Creating the method to take screenshot in the Base class
public void getScreenshot(String result) throws IOException
{
File dest=new File("D:\\Work\\KT\\Scr Shot\\"+result+"test.png");
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, dest);
}
}
}
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.");
}
I use Selenium Web Driver in Eclipse with JUnit. I need create simple checking if some text exists on the page - if it is, than I need generate error. I want this error to be displayed in JUnit failure trace. This is my code:
public class Check {
#Rule
public ErrorCollector errCollector = new ErrorCollector();
#FindBy(tagName="body")
#CacheLookup
private WebElement titl;
#FindBy(partialLinkText="Exception")
#CacheLookup
private WebElement excep;
public void check_false(String t, String r) {
try {
String bodyText = titl.getText();
Assert.assertFalse("Exception found", bodyText.contains(t)); }
catch (AssertionError e) {
System.err.println(r + ": " + e.getMessage());
System.out.println(excep.getText());
errCollector.addError(e);
}
}
If I get error, it is displayed in Eclipse consol, but test if shown as without error in JUnit and no exception message is displayed. How can I make checking properly?
I use
AssertJUnit.assertFalse("Exception found", bodyText.contains(t));
It's from http://testng.org/doc/index.html
see http://testng.org/javadoc/org/testng/AssertJUnit.html
Within eclipse when my test fails, in the junit window I get the stackstrace. Have never tried collecting the errors. It would throw an
AssertionFailedError
if the test fails but if you catch it, I don't know if the stacktrace will be in the JUnit window.
This might not be quite what you're after, in which case ignore it, but you can simply fail it and supply an optional message as to why.
public void checkText(String actual, String expected){
try{
if(!expected.equals(actuals){
fail("Expected : [ " expected + " ] , actual [" + actual + "]"
}catch(SomeOtherException soe){
fail(soe.getMessage());
}
}