TDD流程
.功能测试
.单元测试
."单元测试/编写代码"循环
.重构
总体流程参考如图:
首先编写一个测试,运行测试看着失败,然后编写最少量的代码取得一些进展,再运行测试,循环直到成功为止
如果又有功能测试,又有单元测试,把功能测试当做循环高层视角,即编写程序让这个代码通过。
功能测试是应用能否运行的最终评判,而单元测试则是整个开发过程中的一个辅助工具
下面是一个例子:
使用TDD Python Django开发一个网页,网页的的title是first_TDD,包含一个标签h1,h1内容为Hello World
新建一个django,里面包括一个app Helloworld
新建一个功能测试test1.py
from selenium import webdriver import unittest class Myunittest(unittest.TestCase): def setUp(self):#测试开始前运行 self.browser=webdriver.Firefox() def tearDown(self):#测试开始后运行 self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self):#测试的主要方法 self.browser.get("http://127.0.0.1:8000") self.assertIn("first_TDD",self.browser.title)#断言 head_text=self.browser.find_element_tag_name(‘h1‘).text self.assertIn("Hello World",head_text)#断言 #self.fail("Finish test")#提前结束测试 if __name__==‘__main__‘: unittest.main(warnings=‘ignore‘)#启动unittest测试程序
运行功能测试出现错误:
AssertionError: ‘first_TDD‘ not found in ‘Django: the Web framework for perfectionists with deadlines.‘
修改HelloWorld下的tests.py(自带单元测试)
from django.test import TestCase from django.urls import resolve from Helloworld.views import hello from django.template.loader import render_to_string class HomepageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve(‘/‘) # 测试网站url(这里是网站跟路径)的关系是否如愿 self.assertEqual(found.func, hello) # 看看是否能找到名为home_page的函数 def test_home_page_returns_correct_html(self): respose=self.client.get(‘/‘) self.assertTemplateUsed(respose,‘hello.html‘)#检测响应是用哪个模板渲染的
AttributeError: module ‘Helloworld.views‘ has no attribute ‘hello‘
在Helloworld修改views.py
def hello(request): pass
循环单元测试 编写代码通过 直到功能测试通过
最终在templates新建hello.html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>first_TDD</title> </head> <body> <h1>Hello World</h1> </body> </html>
Helloworld下面的views.py
from django.shortcuts import render def hello(request): return render(request,‘hello.html‘)
first_TDD下面的urls.py
from django.conf.urls import url from Helloworld import views urlpatterns=[ url(r‘^$‘,views.hello) ]
最终单元测试运行 python manage.py test通过
Ran 2 tests in 0.007s
OK
功能测试python test1.py通过
---------------------------------------------------------------------
Ran 1 test in 7.483s
OK
整个开发流程完成
注意:我用pycharm创建的django app加入不用修改settings.py,其他可能要 修改如下
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
’Helloworld‘,
]
既可以把创建的app注册入工程
原文:https://www.cnblogs.com/chenminyu/p/11728990.html