Невозможно щелкнуть элемент внутри динамической веб-таблицы в Селен C # - PullRequest
0 голосов
/ 16 мая 2018

У меня есть метод таблицы, и я использую этот метод для чтения и щелчка элементов внутри динамической веб-таблицы. Я не могу щелкнуть элемент внутри таблицы. Я получаю 'Индекс был вне диапазона. Должен быть неотрицательным и меньше размера ошибки коллекции.

Я пытаюсь удалить 'файл теста QA, созданный скриптом автоматизации' из таблицы.

Сообщение об ошибке и код:

Любая помощь с этим будет очень признателен, спасибо.

Сообщение об ошибке:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at System.Collections.ObjectModel.ReadOnlyCollection`1.get_Item(Int32 index)
   at Automation.TablePage.ReadTable(IWebElement table) in C:\Madhan\-localRepo\Automation\Automation\TablePage.cs:line 47
   at Automation.FunstionalTestPage.TestPage() in C:\Madhan\-localRepo\Automation\Automation\FunstionalTestPage.cs:line 313

Ошибка следующего кода:

Error on code in Test class :

    Code : tablePage.ReadTable(tablePage.table);

	Error on code in  Table Method :
  
	 tableDatacollections.Add(new TableDatacollection
      {
           RowNumber = rowIndex,
            ColumnName = columns[colIndex].Text != "" ?
                         columns[colIndex].Text : colIndex.ToString(),
                        ColumnValue = colValue.Text,
                        ColumnSpecialValues = colValue.Text != "" ? null :
                                                colValue.FindElements(By.TagName("input"))
                        });

HTML код:

<table id="audits" class="dataTable">
  <thead>
    <tr>
      <th></th>
      <th></th>
      <th>Title</th>
      <th>Result</th>
      <th>Date Created</th>
      <th>Created By</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="button" class="roundedButton enableSubmitButton" onclick="continueAudit('1146');" value="Continue"></td>
      <td><input type="button" class="roundedButton btnDisableDoubleClick" onclick="deleteAudit('1146');" value="Delete"></td>
      <td>
        <div id="displayDiv1146" style="width:100%;"><img src="/images/Buttons/Selected/edit.png" title="Edit this submission approval's title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="hideShowEditRow(1146, true);"><span id="displaySpan1146"
            style="padding-left: 5px; width:100%; word-wrap:break-word; white-space: normal;"></span></div>
        <div id="editDiv1146" style="display: none;"><img src="/images/Buttons/Selected/accept.png " title="Save changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="submitAuditTitleChange(1146);"><img src="/images/Buttons/Selected/cancel.png "
            title="Discard changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 4px; cursor: pointer;" onclick="hideShowEditRow(1146, false);"><input type="text" id="editTxt1146" style="width: calc(100% - 48px);"></div>
      </td>
      <td>False</td>
      <td>5/16/2018 2:19:44 PM</td>
      <td>Madhan</td>
    </tr>
    <tr>
      <td><input type="button" class="roundedButton enableSubmitButton" onclick="continueAudit('1147');" value="Continue"></td>
      <td><input type="button" class="roundedButton btnDisableDoubleClick" onclick="deleteAudit('1147');" value="Delete"></td>
      <td>
        <div id="displayDiv1147" style="width:100%;"><img src="/images/Buttons/Selected/edit.png" title="Edit this submission approval's title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="hideShowEditRow(1147, true);"><span id="displaySpan1147"
            style="padding-left: 5px; width:100%; word-wrap:break-word; white-space: normal;">QA Test file created by automation script</span></div>
        <div id="editDiv1147" style="display: none;"><img src="/images/Buttons/Selected/accept.png " title="Save changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="submitAuditTitleChange(1147);"><img src="/images/Buttons/Selected/cancel.png "
            title="Discard changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 4px; cursor: pointer;" onclick="hideShowEditRow(1147, false);"><input type="text" id="editTxt1147" style="width: calc(100% - 48px);"></div>
      </td>
      <td>False</td>
      <td>5/16/2018 2:25:16 PM</td>
      <td>Madhan</td>
    </tr>
    <tr>
      <td><input type="button" class="roundedButton enableSubmitButton" onclick="continueAudit('1148');" value="Continue"></td>
      <td><input type="button" class="roundedButton btnDisableDoubleClick" onclick="deleteAudit('1148');" value="Delete"></td>
      <td>
        <div id="displayDiv1148" style="width:100%;"><img src="/images/Buttons/Selected/edit.png" title="Edit this submission approval's title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="hideShowEditRow(1148, true);"><span id="displaySpan1148"
            style="padding-left: 5px; width:100%; word-wrap:break-word; white-space: normal;">test 3</span></div>
        <div id="editDiv1148" style="display: none;"><img src="/images/Buttons/Selected/accept.png " title="Save changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 2px;  cursor: pointer;" onclick="submitAuditTitleChange(1148);"><img src="/images/Buttons/Selected/cancel.png "
            title="Discard changes to the title." style="width: 20px; height: 20px; margin-left: 2px; margin-right: 4px; cursor: pointer;" onclick="hideShowEditRow(1148, false);"><input type="text" id="editTxt1148" style="width: calc(100% - 48px);"></div>
      </td>
      <td>False</td>
      <td>5/16/2018 2:25:28 PM</td>
      <td>Madhan</td>
    </tr>
  </tbody>
</table>

[Web Table[1]

[Test class]:


TablePage tablePage = new TablePage();

// Read Table

    tablePage.ReadTable(tablePage.table);
	
// Get the cell value from the table

    tablePage.ReadCell("Title", 2);
    Console.WriteLine(tablePage.ReadCell("Title", 1));
     Console.Read();

//Click delete for QA Test file created by automation script

    tablePage.PerformActionOnCell("2","Title", "QA Test file created by automation script", "Delete");
	
//Click continue for : QA Test file created by automation script
	
	tablePage.PerformActionOnCell("1", "Title", "QA Test file created by automation script", "Continue");

Метод таблицы:

namespace Automation
    {
    public class TablePage : BaseTest
        {
        public TablePage()
            {
            PageFactory.InitElements(BaseTest.Driver, this);

            }

        [FindsBy(How = How.TagName, Using = "table")]

        public IWebElement table { get; set; }



        static List<TableDatacollection> tableDatacollections = new List<TableDatacollection>();
        public void ReadTable(IWebElement table)
            {
            //Get all the columns from the table
            var columns = table.FindElements(By.TagName("th"));

            //Get all the rows
            var rows = table.FindElements(By.TagName("tr"));

            //Create row index
            int rowIndex = 0;

            foreach (var row in rows)
                {
                int colIndex = 0;

                var colDatas = row.FindElements(By.TagName("td"));

                foreach (var colValue in colDatas)
                    {
                    tableDatacollections.Add(new TableDatacollection
                        {
                        RowNumber = rowIndex,
                        ColumnName = columns[colIndex].Text != "" ?
                                    columns[colIndex].Text : colIndex.ToString(),
                        ColumnValue = colValue.Text,
                        ColumnSpecialValues = colValue.Text != "" ? null :
                                              colValue.FindElements(By.TagName("input"))
                        });

                    //Move to next column
                    colIndex++;
                    }
                rowIndex++;
                }


            }

        public string ReadCell(String columnName, int rowNumber)
            {
            var data = (from e in tableDatacollections
                        where e.ColumnName == columnName && e.RowNumber == rowNumber
                        select e.ColumnValue).SingleOrDefault();
            return data;

            }

        //PerformActionOnCell
        public void PerformActionOnCell(string columnIndex, string refColumnName, string refColumnValue,
            string controlToOperate = null)
            {
            foreach (int rowNumber in GetDynamicRowNumber(refColumnName, refColumnValue))
                {
                var cell = (from e in tableDatacollections
                            where e.ColumnName == columnIndex && e.RowNumber == rowNumber
                            select e.ColumnSpecialValues).SingleOrDefault();


                //Need to operate on those controls
                if (controlToOperate != null && cell != null)
                    {
                    var returnedControl = (from c in cell
                                           where c.GetAttribute("value") == controlToOperate
                                           select c).SingleOrDefault();

                    returnedControl?.Click();
                    }
                else
                    {
                    cell?.First().Click();
                    }
                }
            }



        private static IEnumerable GetDynamicRowNumber(string columnName, string columnValue)
            {

            //dynamic row
            foreach (var table in tableDatacollections)
                {
                if (table.ColumnName == columnName && table.ColumnValue == columnValue)
                    yield return table.RowNumber;
                }

            }


        public class TableDatacollection
            {
            public int RowNumber { get; set; }
            public string ColumnName { get; set; }
            public string ColumnValue { get; set; }
            public ReadOnlyCollection<IWebElement> ColumnSpecialValues { get; set; }

            public static void Add(TableDatacollection tableDatacollection)
                {
                //throw new NotImplementedException();
                }
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...