Skip to content

Instantly share code, notes, and snippets.

@dzharii
Created March 31, 2012 19:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dzharii/2267565 to your computer and use it in GitHub Desktop.
Пример 01: Первоначальный тест кейс + все необходимые декларации страницы Google.
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System.Collections.Generic;
using System;
using NUnit.Framework;
namespace Selenium.Two.DotNetExample
{
[TestFixture]
class TestGoogle_Initial
{
IWebDriver driver;
[SetUp]
public void Setup()
{
driver = new InternetExplorerDriver();
}
[TearDown]
public void Teardown()
{
driver.Quit();
}
// =================== Google page ==================================
public class GoogleSearchPage
{
IWebDriver drv;
string DefaultUrl = "http://www.google.com";
public IWebElement QueryBox { get { return drv.FindElement(By.Name("q")); } }
public GoogleSearchPage(IWebDriver drv)
{
this.drv = drv;
}
public void Show()
{
Show(DefaultUrl);
}
public void Show(string url)
{
//Navigate to the site
drv.Navigate().GoToUrl("http://www.google.com");
}
public void Search(string searchPhrase)
{
Show();
//Work with the Element that's on the page
QueryBox.SendKeys(searchPhrase);
QueryBox.SendKeys(Keys.Enter);
System.Threading.Thread.Sleep(2000);
}
}
// =================== TESTS ==================================
[Test]
public void TestSearchGoogleForThisIsATest()
{
// Actual: "this is a test - Поиск в Google"
// * Arrange
IWebDriver selenium = new InternetExplorerDriver();
var googlePage = new GoogleSearchPage(selenium);
string googleSearchPhrase = "This is a test";
// * Act
googlePage.Search(googleSearchPhrase);
// * Assert
// 1. Should contain the search phrase
StringAssert.Contains(googleSearchPhrase, selenium.Title);
// 2. Should contain our Company name
StringAssert.Contains("Google", selenium.Title);
}
}
}
// Пример 02: Использование константы isBOOGLE_01_fixed.
// Примечание: Все константы должны храниться в отдельном файле, специально предназначенном для хранения констант для обходов. В данном примере, только ради укрощения, константа объявляется рядом с тест-кейсом.
// Google Instant search should not always display the search phrase in lower case
const bool isBOOGLE_01_fixed = false;
// =================== TESTS ==================================
[Test]
public void TestSearchGoogleForThisIsATestWorkaround00()
{
// Actual: "this is a test - Поиск в Google"
// * Arrange
IWebDriver selenium = new InternetExplorerDriver();
var googlePage = new GoogleSearchPage(selenium);
string googleSearchPhrase = "This is a test";
if (!isBOOGLE_01_fixed)
{
Console.WriteLine("Workaround for BOOGLE-01 Google Instant search should not always display the search phrase in lower case");
googleSearchPhrase = googleSearchPhrase.ToLower();
}
// * Act
googlePage.Search(googleSearchPhrase);
// * Assert
// 1. Should contain the search phrase
StringAssert.Contains(googleSearchPhrase, selenium.Title);
// 2. Should contain our Company name
StringAssert.Contains("Google", selenium.Title);
}
// Пример 03: Усовершенствованный пример с использованием списка обходов и метода UseWorkAround
// Примечание: Все константы, список обходов и функции для работы с Workaround’ами должны храниться в отдельном файле. Для упрощения примера, я объявил их рядом с тест-кейсом.
const string BOOGLE_01 = "BOOGLE-01";
// BugId, "Bug Description"
public static Dictionary<string, string> Workarounds = new Dictionary<string, string>()
{
{BOOGLE_01, "Google Instant search should not always display the search phrase in lower case"},
// {BOOGLE_02, "Google Crashes"}, // Fixed in version 1.00.333
};
public static bool UseWorkAround(string bugId)
{
bool useWorkAround = false;
if (Workarounds.ContainsKey(bugId))
{
Console.WriteLine("Workaround for {0} - {1} was used", bugId, Workarounds[bugId]);
useWorkAround = true;
}
return useWorkAround;
}
// =================== TESTS ==================================
[Test]
public void TestSearchGoogleForThisIsATestWorkaround01()
{
// Actual: "this is a test - Поиск в Google"
// * Arrange
IWebDriver selenium = new InternetExplorerDriver();
var googlePage = new GoogleSearchPage(selenium);
string googleSearchPhrase = "This is a test";
if ( UseWorkAround(BOOGLE_01) )
googleSearchPhrase = googleSearchPhrase.ToLower();
// * Act
googlePage.Search(googleSearchPhrase);
// * Assert
// 1. Should contain the search phrase
StringAssert.Contains(googleSearchPhrase, selenium.Title);
// 2. Should contain our Company name
StringAssert.Contains("Google", selenium.Title);
}
// Пример 04: Универсальный метод WorkaroundFor для подавления возможных исключений в результате проверок
/* Примечание: Вторым параметром, метод WorkaroundFor(string bugId, Action testCode) принимает универсальный (любой) тестовый код. В языке C# это возможно благодаря поддержке замыканий и лямбда-выражениям. Предшественниками лямбда-выражений в языке C# были делегаты, также известные, как анонимные функции.
Смотрите также:
* Лямбда-выражения (Руководство по программированию в C#) < http://msdn.microsoft.com/ru-ru/library/bb397687.aspx >
* Анонимные функции (Руководство по программированию на C#) < http://msdn.microsoft.com/ru-ru/library/bb882516.aspx >
* Замыкания в языке C# < http://www.rsdn.ru/article/csharp/Closure_in_Csharp.xml >
* Википедия: Замыкание (программирование) < http://ru.wikipedia.org/wiki/Замыкание_(программирование) >
*/
public void WorkaroundFor(string bugId, Action testCode)
{
if (UseWorkAround(bugId))
{
try
{
testCode();
}
catch (Exception exception) // Suppress exception
{
Console.WriteLine("Workaround error:");
Console.WriteLine(exception.ToString());
}
}
else
{
testCode();
}
}
// =================== TESTS ==================================
[Test]
public void TestSearchGoogleForThisIsATestWorkaround04()
{
// Actual: "this is a test - Поиск в Google"
// * Arrange
IWebDriver selenium = new InternetExplorerDriver();
var googlePage = new GoogleSearchPage(selenium);
string googleSearchPhrase = "This is a test";
// * Act
googlePage.Search(googleSearchPhrase);
// * Assert
// 1. Should contain the search phrase
WorkaroundFor(BOOGLE_01,
() => StringAssert.Contains(googleSearchPhrase, selenium.Title)
);
// 2. Should contain our Company name
StringAssert.Contains("Google", selenium.Title);
}
/*
Пример 05: Более сложный пример с дескрипторами
Примечание: Во множестве случаев, простого списка обходов, в котором содержится идентификатор бага и его текстовое описание (заголовок), вполне хватает для успешной работы.
*/
const string BOOGLE_01 = "BOOGLE-01";
// BugId, "Bug Description"
public static Dictionary<string, string> Workarounds = new Dictionary<string, string>()
{
{BOOGLE_01, "Google Instant search should not always display the search phrase in lower case"},
// {BOOGLE_02, "Google Crashes"}, // Fixed in version 1.00.333
};
/*
Но, возможны и такие ситуации, когда автоматизация запускается на разных операционных системах и локализациях. И иногда появляются баги, которые воспроизводятся на Windows XP, но не воспроизводятся в Windows 7; воспроизводятся на китайском языке, но не воспроизводятся на русском.
В таких ситуациях, следует указать более детальную информацию о баге, и для этого список Workarounds усложняется дескриптором:
*/
class BugDescriptorExample
{
public class BugDescriptor
{
public bool IsFixed { get; set; }
public string Title { get; set; }
public string[] OS { get; set; }
public string[] Lang { get; set; }
public string[] Browser { get; set; }
}
const string BOOGLE_02 = "BOOGLE-02";
const string BOOGLE_01 = "BOOGLE-01";
// BugId, "Bug Description"
public static Dictionary<string, BugDescriptor> Workarounds = new Dictionary<string, BugDescriptor>()
{
{BOOGLE_01, new BugDescriptor()
{
IsFixed = false,
Title = "Google Instant search should not always display the search phrase in lower case",
OS = new string[] {"XP", "Vista"},
Lang = new string[] {":all"},
Browser = new string[] {":all"},
}},
{BOOGLE_02, new BugDescriptor()
{
IsFixed = true,
Title = "Google Crashes",
OS = new string[] {"XP", "Vista"},
Lang = new string[] {":all"},
Browser = new string[] {":all"},
}},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment