Presentation is loading. Please wait.

Presentation is loading. Please wait.

Тестирование UI. Джентельменский набор MVP NUnit NUnitForms RhinoMocks(NMock) Windows PowerShell.

Similar presentations


Presentation on theme: "Тестирование UI. Джентельменский набор MVP NUnit NUnitForms RhinoMocks(NMock) Windows PowerShell."— Presentation transcript:

1 Тестирование UI

2 Джентельменский набор MVP NUnit NUnitForms RhinoMocks(NMock) Windows PowerShell

3 Тестирование UI Код, который легко тестировать Тесты, которые легко «кодить»

4 Model View Controller Model View Controller

5 Model View Controller Model Controller Display logic Presen- tation logic View

6 MVP Model View Presenter Event/Observer Model View Presenter

7

8 MVP public interface IOrderView { string Name {get;set;} int Amount {get;set;} void ShowMessage(string message); event VoidDelegate Cancel; event VoidDelegate Save; } public interface IEmailService { bool SendEmail(string email, string text); } Model View Presenter

9 MVP public class OrderPresenter { private IEmailService service; private IOrderView view; public OrderPresenter(IEmailService service, IOrderView view) { this.view = view; this.service = service; view.Save += view_Save; } void view_Save() { Order order = new Order(view.Name, view.Amount); if(order.Amount > 1000) service.SendEmail("vasya@email.com", "Order amount > 1000"); //Process order... } Model View Presenter

10 State-based тестирование Тестирование «чистых» функций Тестирование компонентов с малым числом зависимостей Тестирование компонентов обладающих «простыми состояниями»

11 State-based тестирование public class StateBasedUnitTest { public void DoTest() { Calculator calc = new Calculator(); int res = calc.Sum(10, 20); Assert.AreEqual(res, 30); }

12 К сожалению, Presenter… Не предоставляет «чистых функций» Будучи по своей природе «медиатором», зависит от большого числа компонентов Тестировать состояние Presenter-а абсолютно бесмысленое занятие

13 Пример тестового сценария Сотрудник вводит в форму «Создание заказа» название и стоимость заказа Пользователь нажимает кнопку «Сохранить заказ» Если стоимость заказа превышает 1000 рублей, то посылается email главному менеджеру для проверки заказа Заказ сохраняется в системе Пользователю сообщается, что заказ успешно сохранился в системе

14 public void DoTest() { MockRepository mocks = new MockRepository(); //Создание mock-объектов IEmailService emailService = mocks.CreateMock (); IOrderView view = mocks.CreateMock (); //Начало записи сценария view.Save += null; IEventRaiser raiser = LastCall.IgnoreArguments().GetEventRaiser(); using(mocks.Unordered()) { Expect.Call(view.Name).Return("Beer"); Expect.Call(view.Amount).Return("1001"); } Expect.Call(emailService.SendEmail("", "")).IgnoreArguments(); Expect.Call(view.ShowMessage("")).IgnoreArguments(); //Проигрываем сценарий и проверяем соответствие записанному mocks.ReplayAll(); OrderPresenter presenter = new OrderPresenter(emailService, view); raiser.Raise(); mocks.VerifyAll(); } Реализация interaction-based тестирования с RhinoMocks

15 NUnitForms public void Test() { Form1 form = new Form1(); form.Show(); TextBoxTester tbxName = new TextBoxTester("Name2"); TextBoxTester tbxAmount = new TextBoxTester("Amount2"); ButtonTester btnOK = new ButtonTester("btnOk"); FormTester appForm = new FormTester("Form1"); ExpectModal("Message", delegate { MessageBoxTester messageBox = new MessageBoxTester("Message"); messageBox.ClickOk(); }); tbxName.Enter("Beer"); tbxAmount.Enter("1001"); btnOK.Click(); form.Dispose(); }

16 Windows PowerShell Windows PowerShell™ — это новая командная оболочка Windows, разработанная в первую очередь для системных администраторов. Она включает интерактивную командную строку и среду исполнения сценариев.

17 Windows PowerShell Понятие командлета(сmdlet) в Windows PowerShell Создание своих командлетов на.Net Использование готовых библиотек Cmdlet-ов для автоматизации тестирования UI

18 Custom Cmdlets for UI Automation Cmdlet NameInput ParametersReturn Value / Effect get-windowwindowNameHandle to a top-level window get-controlhandleParent, ctrlNameHandle to a named control get-controlByIndexhandleParent, indexHandle to a non-named control send-charshandleControl, sSends string s to a control send-clickhandleControlClicks a control get-listBoxhandleControl, targetZero-based location of target get-textBoxhandleControlContents of TextBox as a string send-menumainIndex, subIndexFires application menu command.

19 Windows PowerShell # Test.ps1 write-host "Start test" $testPassed = $true invoke-item 'TestApp.exe' [System.Threading.Thread]::Sleep(2000) #get handlers $app = get-window "TestApp" $tbxName = get-control $app "Name" $tbxAmout = get-control $app "Amount" $btnOk = get-control $app "Ok" #init form send-chars $tbxName "Beer" send-chars $tbxAmout "1001" send-click $btnOk #... #get message box [System.Threading.Thread]::Sleep(2000) $mBox = get-window "Message" if( $mBox –eq $null ) { write-host “Test failed” } else { write-host "`Test passed" } write-host "End test" # end script

20 Windows PowerShell public class TestScript { public string CreatedBy{...} public string DateCreated{...} public int Priority{...} public string Tags{...} public int ExecutionTime{...} public int LastExecutionTime{...} } [Cmdlet(VerbsLifeCycle.Start, "TestScripts")] public class ExecuteScripts : Cmdlet {... private void executeScripts(TestScript[] scripts){...} } [Cmdlet(VerbsCommon.Get, "TestScripts")] public class GetScripts : Cmdlet {... private TestScript[] findScripts(string path){...} }

21 PS C:\> Get-TestScripts –Path.\MyTests | Where-Object -FilterScript {($_.Tags -contains "Order") -or ($_. Tags -contains "Customer")} | Execute-TestScripts PS C:\> Get-TestScripts –Path.\MyTests | Where-Object -FilterScript {($_. Tags -contains "Order")} | Sort-Object -Priority -Descending | Execute-TestScripts PS C:\> Get-TestScripts –Path.\MyTests | Where-Object -FilterScript {($_.Tags - contains "Order") –and ($_.CreatedBy -eq “Maxim") } | Sort-Object -CreatedTime -Descending | Execute-TestScripts Windows PowerShell

22 Коротков Максим, Finance Software www.financesoftware.ru email: maxim.korotkov@gmail.commaxim.korotkov@gmail.com Windows PowerShell


Download ppt "Тестирование UI. Джентельменский набор MVP NUnit NUnitForms RhinoMocks(NMock) Windows PowerShell."

Similar presentations


Ads by Google