Friday, September 16, 2016

Using ExtentReports with MSTest framework on C#

When i was dealing with coded UI ,Selenium and Appium test result reporting i found this super cool reporting framework called "ExtentReports".





I love the UI.
And this can be use with MSTest and Nunit framework too.

Below are the steps to how to deal with the ExtentReports on MSTest.

1.     Downloadthe latest ExtentReports DLL, or use this command with NuGet manager.
Install-Package ExtentReports
2.     Add the downloaded file as a reference.
3.     Use the namespace “using RelevantCodes.ExtentReports;” in order to use the newly downloaded dll.
4.     Then on your test project at the class level define below variables;
·         public static ExtentTest test { get; set; }
·         public static ExtentReports extent { get; set; }
·         public TestContext TestContext { get; set; }

5.     Use an assembly initialize attribute and provide the folder for the HTML report.
[AssemblyInitialize]
static public void TestSetUp(TestContext TestContext)
{
extent = new ExtentReports("../../Reports/ExtentScreenshot.html", true);
        }

6.  Inside your test method write down the things or steps that you are performing by the Extended Reports way as on below.

[TestMethod]
        public void Test_OtherTestatNewClass()
        {

            test = extent.StartTest("Test case one");<-Test case name.

            test.Log(LogStatus.Pass, "Start Compairing two values");<-Explain the step
            Assert.AreEqual("123", "1233");
            test.Log(LogStatus.Pass, "End Compairing two values");

            LogStatus status = test.GetCurrentStatus();
            test.Log(LogStatus.Info, "Test Finished");
            test.Log(LogStatus.Info, status.ToString());  
            test.Log(LogStatus.Pass, "Test Passed");
        }

7.  Then use a test cleanup method and it will do the things if the above test get failed.
[TestCleanup]
        public void LogError()
        {
         
            var status = TestContext.CurrentTestOutcome.ToString();
            var status2 = Console.Error.ToString();

            this.TestContext.WriteLine(Console.Error.ToString());

            if (status =="Failed")
            {
                test.Log(LogStatus.Fail);
                test.Log(LogStatus.Fail,"Test Failed");
              

            }
           
            extent.EndTest(test);
        }

8.  Then at last use an assembly cleanup method in order to write everything to the the HTML file

[AssemblyCleanup]
        static public void EndReport()
        {
            extent.Flush();       
            extent.Close();
        }

DONE

Wednesday, June 1, 2016

Trouble shooting error messages on selenium C# -02

I faced below exception :( 

Test method AppiumDTZ.Test_ProfilePage.Validate_Updating_Mobile_Phone_umber threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: unknown error: Element is not clickable at point (180, 546). Other element would receive the click: <div class="bar bar-footer ugl-footer app-common-footer" dtz-hide-on-keyboard-show="">...</div>
  (Session info: webview=33.0.0.0)
  (Driver info: chromedriver=2.18.343845 (73dd713ba7fbfb73cbb514e62641d8c96a94682a),platform=Windows NT 6.3 x86_64)
Result StackTrace:

Root course for this was, the element which im try to click was under a transparent element.
The transparent layer was static and cant move.

So when ever i try to click on the button it will search on the transparent layer.
There for i have to scroll the bottom layer to the top or the maximum  to get my button out of the transparent layer.

I tried with different mechanisms to scroll the layer but nothing works for me except this.


                IJavaScriptExecutor js = (IJavaScriptExecutor)InitialiseAppium.driver;
                js.ExecuteScript("arguments[0].scrollIntoView()", <elemant name>);

Monday, May 30, 2016

Trouble shooting error messages on selenium c# -01

The CLR has been unable to transition from COM context 0x12aa9d0 to COM context 0x12aab40 for 60 seconds.

Above message is bit weird error message.


This happens to me in  middle of  debugging a selenium code via visual studio 2012.

Solution :
Debug -> Exceptions -> Managed Debug Assistants menu in Visual Studio and uncheck the ContextSwitchDeadlock

reff :http://stackoverflow.com/questions/2747916/the-clr-has-been-unable-to-transition-from-com-context-for-60-seconds


Thursday, May 26, 2016

Automatically run CodedUI test methods by scheduled tasak

1).Create the test methods and run it thru the test explorer at the visual studio.
You should get the green color test pass view at the test explorer.


2).Navigate to solution explorer and click on "Open folder on file explorer"

3.Inside the bin\debug find the .dll file.
There will we only one dll file.

4).Open a note pad and write down below things.

//Navigate to the debug folder where you found at the step 3.
cd "E:\Users\cja\documents\visual studio 2012\Projects\PowerBI\PowerBI\bin\Debug"

//some times windows will fail to navigate to the exact location so have to do this.Mos of the time this happens when the cd command contain some other drive rather than "C" drive.
e:

//Find the MSTest.exe path and add it to a variable.
Most of the time below is the default location of the MSTest.exe .
set mstestPath="C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE"

//we use the above variable and then the MSTest.exe file and then a keyword.
Keyword should be pointing tot the dll whcih we found at step 3.
%mstestpath%\mstest /testcontainer:PowerBI.dll

5).Save the file as a bat file
6).Make a scheduled task using the above bat file. :)



Tuesday, May 10, 2016

Important things on Appium - 2

I got a time out error as on the below.
I have highlighted the most important area of the error message.

Test Name: Validate_Availability_Of_Valid_Completion_By_Date_And_Time_At_Workorder_Details
Test FullName: AppiumDTZ.Test.Test_WorkOrderDetails.Validate_Availability_Of_Valid_Completion_By_Date_And_Time_At_Workorder_Details
Test Source: e:\QA automation\appium\AppiumTFS\DTZAppium\AppiumDTZ\AppiumDTZ\Test\Test_WorkOrderDetails.cs : line 87
Test Outcome: Failed
Test Duration: 0:00:00

Result Message: Assembly Initialization method AppiumDTZ.Test_LandingPage.testinitialisation threw exception. OpenQA.Selenium.WebDriverException: OpenQA.Selenium.WebDriverException: The HTTP request to the remote WebDriver server for URL http://127.0.0.1:4723/wd/hub/session timed out after 60 seconds. ---> System.Net.WebException: The request was aborted: The operation has timed out.. Aborting test execution.
Result StackTrace:
at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
 --- End of inner exception stack trace ---
    at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
   at OpenQA.Selenium.Remote.HttpCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(Uri remoteAddress, ICapabilities desiredCapabilities)
   at AppiumDTZ.InitialiseAppium.AppiumSetupMethod() in e:\QA automation\appium\AppiumTFS\DTZAppium\AppiumDTZ\AppiumDTZ\InitialiseAppium.cs:line 41
   at AppiumDTZ.Test_LandingPage.testinitialisation(TestContext context) in e:\QA automation\appium\AppiumTFS\DTZAppium\AppiumDTZ\AppiumDTZ\Test\Test_LandingPage.cs:line 24


The solution was add a time stamp to the place where you initialize the appium web driver or remote web driver or what ever the driver.
By default it has set to 60 seconds.


driver = new RemoteWebDriver (new Uri("http://127.0.0.1:4723/wd/hub"), capabilities,TimeSpan.FromSeconds(180));

Wednesday, May 4, 2016

Important things on CodedUI

If you need to add any costume text to your test out put.
just try adding highlighted text to your test method.


        [TestCategory("Work Order List"), TestMethod]
        public void Validate_WorkOrder_Search_By_Asset_Barcode()
        {
            ElemantsWODetails elm = new ElemantsWODetails();
            string WorkOrderAssetNumber = "QAZWSXEDC123";
            string ExpectedAssetBarcode=elm.ValidateSearchWOByBarcode("QAZWSXEDC123");
            Assert.AreEqual(ExpectedAssetBarcode, WorkOrderAssetNumber);
            elm.ClickOnDoneButton();
            this.TestContext.WriteLine("Expected Result :" + ExpectedAssetBarcode + "  Actual Result : " + WorkOrderAssetNumber + "");

        }

Out put.

Wednesday, April 27, 2016

Important things on Appium

When we are testing a hybrid application we will have main two types of windows.
1.WEBVIEW
2.NATIVE_APP

So always keep in mind to switch between the relevant window when you perform the correct task or action.

eg:
driver.SwitchTo().Window("WEBVIEW")
driver.SwitchTo().Window("NATIVE_APP")


Some times you might have to deal with one native app and more than 1 webviews .
So get the web view names by below code and switch to the correct window.

ReadOnlyCollection<string> windowHandles = InitialiseAppium.driver.WindowHandles;
driver.SwitchTo().Window(windowHandles[1]);

Wednesday, March 9, 2016

Element is not clickable at point



I was facing the same issue while im on my project and i was stucked at the same issue for more than 6 hours

I was with selenium on c#

My original issue was :
I have bold the most important area. 

Result Message:
Test method FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.ValidateCloseButton threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: unknown error: Element is not clickable at point (514, 158). Other element would receive the click: <div class="row">...</div>
  (Session info: chrome=48.0.2564.109)
  (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64)
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebElement.Click()
 --- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at OpenQA.Selenium.Support.PageObjects.WebDriverObjectProxy.InvokeMethod(IMethodCallMessage msg, Object representedValue)
   at OpenQA.Selenium.Support.PageObjects.WebElementProxy.Invoke(IMessage msg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at OpenQA.Selenium.IWebElement.Click()
   at FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.Clickbackbutton() in e:\Focus\FocusTest\FocusTest\TestPropertyOnaPage\TestPropertyOnaPage.cs:line 82
   at FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.ValidateCloseButton() in e:\Focus\FocusTest\FocusTest\TestPropertyOnaPage\TestPropertyOnaPage.cs:line 111




Then after doing some various fixes i got the same issue with a different error message.

Result Message:
Test method FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.ValidateCloseButton threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> OpenQA.Selenium.ElementNotVisibleException: element not visible
  (Session info: chrome=48.0.2564.109)
  (Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Windows NT 6.3 x86_64)
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebElement.SendKeys(String text)
 --- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at OpenQA.Selenium.Support.PageObjects.WebDriverObjectProxy.InvokeMethod(IMethodCallMessage msg, Object representedValue)
   at OpenQA.Selenium.Support.PageObjects.WebElementProxy.Invoke(IMessage msg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at OpenQA.Selenium.IWebElement.SendKeys(String text)
   at FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.ReturnTitleTextForBackButtonValidation(String SearchTxt) in e:\Focus\FocusTest\FocusTest\TestPropertyOnaPage\TestPropertyOnaPage.cs:line 72
   at FocusTest.TestPropertyOnaPage.TestPropertyOnaPage.ValidateCloseButton() in e:\Focus\FocusTest\FocusTest\TestPropertyOnaPage\TestPropertyOnaPage.cs:line 127



Any way my original issue was on my web page there is a small close button, when i try to click on the close button thru the code it gave me the 1st error message.
But the same code working fine in firefox.

So i tryid with :
driver.manage().window().maximize();
Updating chrome driver
IWebElement elementToClick = <code to get element>;

// Scroll the browser to the element's Y position
(driver as IJavaScriptExecutor).ExecuteScript(string.Format("window.scrollTo(0, {0});",
elementToClick.Location.Y));

// Click the element
elementToClick.Click();
// Find an element and define it
WebElement elementToClick = driver.findElement(By.xpath("some xpath"));
// Scroll the browser to the element's Y position
((JavascriptExecutor) driver).executeScript("window.scrollTo(0,"+elementToClick.getLocation().y+")");
// Click the element
elementToClick.click();
IWebDriver driver = new ChromeDriver(@"d:\selenium");
            driver.Navigate().GoToUrl("http://...");

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            IWebElement btn = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.Id("button-xxxx-btnInnerEl"));
            });
            Thread.Sleep(5000); //it works after added this sleep statement
            btn.Click();

Unfortunately nothing is work for me.No damn luck

Finaly i use this code.

            Elements.PropertyOnaPageElm elm = new Elements.PropertyOnaPageElm();
            Actions actions = new Actions(Setup.SetupSeleniumWebDriver.driver);
            actions.MoveToElement(elm.BackButton).Click().Perform();

and it works supper fine.

Thursday, January 28, 2016

Test Post request via Soap UI

Currently Im working on a mobile based project and most of the communications are done with the server by using post requests.
So i started validating the server side requests and response.

Sample Post request will looks like : 

www.<DomainName>.com/API/Language/GetServiceRequestViewModel

Sample Get request will looks like : 

www.<DomainName>.com/API/Language/GetLanguageList


Post request also contain get and get request all so contain get. this is soo funny, LOL.

Configure the POST request.

Open SoupUI and select "New Rest Project" under file menu.



Click on a"OK" and user will get a screen as on the below image.



Click the play button and you dont get nothing,
Because this REST request need to have some parameters to be as inputs, in-order to get some valid output.

There are several ways of inputting parameters to a REST request (it depend on the security level of the REST call and the way developer develop it).

For the below sample test i will be passing data thru the body of the request.


Now change the "Method" type to "POST" next to the play button at the window.

Window should change as on the below image.



For this i need to pass "username" as the input.

There for locate the text box below the "Media type" and set the text as below.

{
    
    UserName:'demo@demo.com'

}




This is how to pass an input thru the body.


Change the media type to "application/json".(Because the response or the output is a json file.)

Now click the play button and you will see there will be some kind of god output will display at the right side of the screen.


That means we have successfully run the POST request with some kind of output.


Configure the a Test-case for a POST request.

Locate the newly created Post request and right click on it.
Select "Add to test case".




You should see a screen as on the below image with a new test suite node at your project.



Run the newly created test suite.
You should get a valid output at right side of the screen, 
That means the configuring of test suite is successfully finished.


Add assertions to a POST request.

Find the assertion tab as on the below image and click on it.

 Click on "Green color Plush" mark an add any kind of assertion.

There are considerable amount of assertions that you can use.
Most useful things are :
  1. Property contains.
  2. Invalid HTTP Status codes.
  3. Valid HTTP Status codes.