0
Тестирование
Alex Slynko
UkrGermanEnterprise
GmbH
URL: www.acceptic.com
Software programming services and
Dedicated develo...
TDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 ...
TDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 ...
Виды тестов
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
T...
Виды тестов
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
T...
Юнит-тесты
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Te...
Тестирование без других частей
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: ...
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 800 ...
Юнит-тесты
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Te...
Интеграционные
● Взаимодействие нескольких систем
● Внешние сервисы могут быть разблокированы
● Медленные
● Может быть нес...
Интеграционные
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.co...
Как TDD работает?
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic...
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 800 ...
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 800 ...
Продаем TDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
T...
Работать с TDD?
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.c...
TDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 ...
Не совсем TDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com...
Примеры
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.:...
Hotel
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +...
Autoleasing
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
T...
TDD. Примеры
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
...
Пример
def calculate_leasing_data
leasing_info = self.leasing_data
options = { :vehicle_id => self.vehicle_id, :ld => leas...
Пример
if output_data and !(output_data == [] or output_data.try(:[], "err").present?
or (records = output_data.try(:[], "...
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 800 ...
Пример
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: ...
Пример
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: ...
Пример
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: ...
Продаем дальше
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.co...
Позволить работать с TDD?
Плюсы
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail:...
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 800 ...
Надо думать
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
T...
Приемочные тесты
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic....
Приемочные
● Given Jira Issue with several bugs
● When all that bugs are fixed
● Then Issue is closed
Взято с Хабра ©
URL:...
Приемочные
● Given Jira Issue with 1 bug
● And I am on issue overview page
● When I fix it
● Then Issue is closed
URL: www...
BDD
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.: +1 ...
Как это работает?
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic...
Позволить работать с BDD?
Плюсы
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail:...
Примеры
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.:...
Примеры
- В комнате должен быть хотя бы один
дееспособный человек
Given a kid client “John”
And an adult client “Jake”
The...
Leasing
Given car which is imported
And I changed it
When I approved it
And run import again
Then car should be still appr...
Как это может не работать?
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info...
Тесты не чиняться
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic...
Неправильные тесты
После работы метода берем результат с которым потом и
сравниваем.
order = Order.build(VAT: 19, discount...
Долгие тесты
URL: www.acceptic.com
Software programming services
and dedicated developers teams
E-mail: info@acceptic.com
...
Сложнотестируемый код
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acce...
Код написанный для тестов
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@...
Взаимозависимые тесты
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acce...
Вера во время
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com...
Порядок
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel.:...
Вопросы?
URL: www.acceptic.com
Software programming services and
Dedicated developers teams
E-mail: info@acceptic.com
Tel....
Upcoming SlideShare
Loading in...5
×

Tdd and BDD

130

Published on

Summary:
- What is TDD?
- What is BDD
- Unit-tests
- Integration tests
- TDD Mantra in detail
- TDD and BDD Pros and Cons

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
130
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Tdd and BDD"

  1. 1. Тестирование Alex Slynko UkrGermanEnterprise GmbH URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  2. 2. TDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  3. 3. TDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Что это такое? ● Test driven development ● Вначале тесты – потом код
  4. 4. Виды тестов URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  5. 5. Виды тестов URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Юнит-тесты ● Интеграционные ● Системные ● Интеграции систем
  6. 6. Юнит-тесты URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Одна часть метода ● К внешним сервисам нет реальных обращений ● Желательно только одна проверка в тесте ● Очень быстро работает
  7. 7. Тестирование без других частей URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Dummy – параметры, которые передаются внутрь, но не используются в тесте. Пустые объекты ● Stub – объекты, которые отвечают на запросы с заданным ответом ● Mock = Stub + проверка, что методы будут вызваны
  8. 8. URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Юнит-тесты context "bonus_data" do context “percent” do should "be taken from trader if absent in model" do @bonus_data_hash = { :percent => 2, :amount => 200 } @trader = OpenStruct.new(:cars_data => {:bonus_data => @bonus_data_hash, :federal_state => "Sachsen" }) @available_car = Car.make_unsaved(:trader => @trader) assert_equal @bonus_data_hash[:percent], @available_car. bonus_data.first[:percent] end end end
  9. 9. Юнит-тесты URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Упрощает рефакторинг – видно где падает ● Самодокументация ● Минимизирует зависимости ● Упрощает интеграцию
  10. 10. Интеграционные ● Взаимодействие нескольких систем ● Внешние сервисы могут быть разблокированы ● Медленные ● Может быть несколько проверок ● В случае изменения старой системы могут работать URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  11. 11. Интеграционные URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 context "the Body overview" do setup do @model = Car::Model.make_with_discount({}, :bonus_data => [ base_bonus(50) ]) end should "show disabled models without link to configure the car" do @model.update_attribute(:enabled, false) visit body_url( @model.brand_slug, @model.line_slug, @model. body_slug ) assert_contain "#{@model.brand_name} #{@model.line_name} # {@model.body_name}" assert_contain I18n.t("show_available_models") assert_have_no_selector "a[href='#{body_models_url( @model. brand_slug, @model.line_slug, @model.body_slug )}']" end
  12. 12. Как TDD работает? URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  13. 13. URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  14. 14. URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Как это работает на самом деле?
  15. 15. Продаем TDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  16. 16. Работать с TDD? URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Плюсы Минусы ● Легче создавать ● Легче рефакторить ● Документация ● Код больше не страшно трогать ● Я не тестировщик ● Не понятно зачем ● Надо поддерживать еще и тесты ● Слишком сложная система
  17. 17. TDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Легко ● Интересно ● Сложно ● Скучно
  18. 18. Не совсем TDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Тесты должны идти в коммите с кодом ● Не весь код должен иметь тесты ● Не совсем помогает
  19. 19. Примеры URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  20. 20. Hotel URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Добавить флажок для гостя, что он ребенок
  21. 21. Autoleasing URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Ежедневно получаем список доступных машин от компании. Добавить checksum и не обновлять машину, если ее checksum такой же как был. should "update car with changes" do AvailableCarsImporter.import car = Car::Available.first car.update_attribute(:trim_level, nil) car.update_attributes({:checksum => 'Changed checksum'}) Car::Available.expects(:save).once AvailableCarsImporter.import assert car.reload.trim_level end
  22. 22. TDD. Примеры URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Нужны ли эти тесты? ● Помогли ли они нам? ● Пригодятся ли в будущем?
  23. 23. Пример def calculate_leasing_data leasing_info = self.leasing_data options = { :vehicle_id => self.vehicle_id, :ld => leasing_info[:runtime].to_i, :jkm => leasing_info[: mileage].to_i, :sozp => leasing_info[:downpayment_percent].to_d.round, :sfan => self.brand_name } becos = options_data.map {|option| option[:option_code] } if options_data options[:becos] = becos if becos.present? output_data = LeasingDataCalculator.get_leasing_data(options) if output_data and !(output_data == [] or output_data.try(:[], "err").present? or (records = output_data.try(:[], "rec")).blank?) and month_rate = records.try(:[], "FL").try(:[], "mrat") delivery_costs_leasing = records.try(:[], "LP").try(:[], "mrat") || 0.0 LeasingData.create( :rate => month_rate.to_d, :offer_id => self.id, :downpayment_percent => leasing_info[: downpayment_percent].to_d.round, :mileage => leasing_info[:mileage], :downpayment_amount => leasing_info[:downpayment_amount].to_d, :runtime => leasing_info [:runtime], :delivery_costs_leasing => delivery_costs_leasing, :additional_info => records.to_json ) else error_message = I18n.t("leasing_data_not_saved", :leasing_offer_id => self.id) Airbrake.notify(:error_class => "CreateLeasingDataError", :error_message => error_message, : parameters => options) end end URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  24. 24. Пример if output_data and !(output_data == [] or output_data.try(:[], "err").present? or (records = output_data.try(:[], "rec")).blank?) and month_rate = records. try(:[], "FL").try(:[], "mrat") delivery_costs_leasing = records.try(:[], "LP").try(:[], "mrat") || 0.0 ... else error_message = I18n.t("leasing_data_not_saved", :leasing_offer_id => self.id) Airbrake.notify(:error_class => "CreateLeasingDataError", : error_message => error_message, :parameters => options) end end URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  25. 25. URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Пример .. output_data = LeasingDataCalculator.get_leasing_data(options) … Class LeasingDataCalculator def self.get_leasing_data(options) return {} if option[:some].blank? #И еще несколько подобных проверок options = prepare_options(options) WebServices.get_leasing_data(options) end end
  26. 26. Пример URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 output_data = { "rec" => { "FL" => { "mrat" => "123.45" }, "LP" => { "mrat" => "234.56" } } } WebServices.stubs(:get_leasing_data).returns(output_data) assert_difference("LeasingData.count") { @offer.calculate_leasing_data } leasing_data = LeasingData.last assert_equal @offer, leasing_data.offer assert_equal 123.45, leasing_data.rate assert_equal 20, leasing_data.downpayment_percent assert_equal 10000, leasing_data.mileage assert_equal 1234, leasing_data.downpayment_amount assert_equal 12, leasing_data.runtime assert_equal 234.56, leasing_data.delivery_costs_leasing assert_equal output_data["rec"].to_json, leasing_data.additional_info
  27. 27. Пример URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 should "notify airbrake about not updated leasing data" do WebServices.stubs(:get_leasing_data).returns({"err" => "some error"}) error_message = I18n.translate("leasing_data_not_saved", :leasing_offer_id => @offer.id) Airbrake.expects(:notify).with(:error_class => "CreateLeasingDataError", : error_message => error_message) @offer.calculate_leasing_data end
  28. 28. Пример URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 def calculate_leasing_data output_data = LeasingDataCalculator.get_leasing_data(self) if output_data[:error].blank? LeasingData.create(output_data) else error_message = I18n.t(“create_offer_errors. leasing_data_not_saved", :leasing_offer_id => self.id) Airbrake.notify(:error_class => "CreateLeasingDataError", : error_message => error_message) end end
  29. 29. Продаем дальше URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  30. 30. Позволить работать с TDD? Плюсы URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Минусы ● Довольные программисты ● Уменьшение количества регрессий ● Проще обновлять библиотеки ● Больше времени на задание ● Тяжело роверить ● Отдельный тестовый сервер
  31. 31. URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Последний довод Тесты позволяют писать код не приходя в сознание
  32. 32. Надо думать URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  33. 33. Приемочные тесты URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Требования выполнены ● Не знает ничего о внутренней структуре (черный ящик) ● Объясняется в терминах заказчика (возможно, даже заказчиком)
  34. 34. Приемочные ● Given Jira Issue with several bugs ● When all that bugs are fixed ● Then Issue is closed Взято с Хабра © URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  35. 35. Приемочные ● Given Jira Issue with 1 bug ● And I am on issue overview page ● When I fix it ● Then Issue is closed URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  36. 36. BDD URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Что это такое? ● Behaviour driven development ● Вначале приемочные тесты – потом код
  37. 37. Как это работает? URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  38. 38. Позволить работать с BDD? Плюсы URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Минусы ● Уменьшение количества регрессий ● Можно проверить что делают ● Улучшается понимание ● Еще больше времени на задание ● Отдельный тестовый сервер
  39. 39. Примеры URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  40. 40. Примеры - В комнате должен быть хотя бы один дееспособный человек Given a kid client “John” And an adult client “Jake” Then I can not reserve room for “John” But I can reserve room for “Jake” And I can reserve room for “Jake” and “John” URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  41. 41. Leasing Given car which is imported And I changed it When I approved it And run import again Then car should be still approved When run import again with different data Then car should be unapproved URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  42. 42. Как это может не работать? URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  43. 43. Тесты не чиняться URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  44. 44. Неправильные тесты После работы метода берем результат с которым потом и сравниваем. order = Order.build(VAT: 19, discount: 5) order.items << (line_item = LineItem.build(price: 100.5)) assert 134.595, order.total_amount ● URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  45. 45. Долгие тесты URL: www.acceptic.com Software programming services and dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Сохраняет данные в базу данных, когда это не нужно order = Order.make(VAT: 19, discount: 5) order.items << (line_item = LineItem.make(price: 100.5)) assert 133.65, order.total_amount
  46. 46. Сложнотестируемый код URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Взаимодествие одного метода с большим количеством объектов public XlsFile GenerateReport() { int period; if (DateTime.Today.DayOfWeek == DayOfWeek.Sunday) { period = 7 } else { period = SomeServiceClient().GetPeriod(); } …
  47. 47. Код написанный для тестов URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 # app/use_cases/post_comment.rb # Called from the "create" action in a controller class PostComment def initialize(user, entry, attributes) @user, @entry, @attributes = user, entry, attributes end def post @comment = @user.comments.new @comment.assign_attributes(@attributes) @comment.entry = @entry @comment.save! LanguageDetector.new(@comment).set_language SpamChecker.new(@comment).check_spam CommentMailer.new(@comment).send_mail post_to_twitter if @comment.share_on_twitter? post_to_facebook if @comment.share_on_facebook? @comment end private def post_to_twitter PostToTwitter.new(@user, @comment).post end def post_to_facebook PostToFacebook.new(@user, @comment).action(:comment) end end
  48. 48. Взаимозависимые тесты URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 ● Изменение конфигурации перед тестом (и не изменение после) ● Сохранение специального конфига в базе данных APP_CONFIG[:available_cars][:traders] = { "TRADER_ID" => @trader.id }
  49. 49. Вера во время URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Запись, которая создается позже имеет timestamp больше bmw = Car.make(:brand_name => ‘bmw’) audi = Car.make(:brand_name => ‘audi’) assert _equal [bwm, audi], Car.order(:created_at).all
  50. 50. Порядок URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370 Порядок не обязан сохраняться, если только он не прописан явно record1 = Car.make(:brand => ‘Audi’) record2 = Car.make(:brand => ‘Audi’) assert_equal [record1, record2], Car.by_brand(‘Audi’)
  51. 51. Вопросы? URL: www.acceptic.com Software programming services and Dedicated developers teams E-mail: info@acceptic.com Tel.: +1 800 990 4370
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×